jQuery slideToggle(从中间点切换)

jQuery slideToggle (Toggle from middle point)

我正在使用 slideToggle(); 方法,它工作正常,我只想从图像的中间点滑入和滑出,而不是向上滑动到左角。 我也不想要 zoomIn 或 zoomOut 事件。

$(document).ready(function() {
  $('.btn').click(function() {
    $('img').stop().slideToggle(5000);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="btn btn-default">My Button</button>
<br><br><br>
<img class="img-responsive" src="http://news.stanford.edu/news/2012/september/images/online_keyboard_news.jpg">

JSFiddle

只需将 img 换成 div

$(document).ready(function() {
  $('.btn').click(function() {
    $('#image_wrapper').slideToggle('slow');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn btn-default">My Button</button>
<br><br><br>
<div id="image_wrapper">
  <img class="img-responsive" src="http://news.stanford.edu/news/2012/september/images/online_keyboard_news.jpg">
</div>

作为使用 jQuery 动画的替代方法,您可以通过对 DOM 结构稍作更改并添加一些css.

const toggleButton = document.getElementById("toggle-button");
const imageContainer = document.getElementById("image-container");

toggleButton.addEventListener("click", () => {
    imageContainer.classList.toggle("show");
});
button {
    position: relative;
    margin: 20px;
}

/* Create a wrapper element that matches the image size */
/* and set it to the desired image reveal size */

.wrapper {
    width: 600px;
    height: 400px;
    position: relative;
    margin: 0 auto;
}

/* Add the image container element and set it to the center of the wrapper */ 
/* set the width and height to 0 so the image isn't visible */

.image {
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    position: absolute;
    background: url(http://news.stanford.edu/news/2012/september/images/online_keyboard_news.jpg)
    no-repeat center center;
    transition-duration: 1000ms;
    transition-timing-function: cubic-bezier(0.5, 0, 1, 1);
}

/* When we want to show the image animate the width and height */
/* to fit the container as well as adjust the margin to keep it centered */

.image.show {
    width: 100%;
    height: 100%;
    position: absolute;
    margin-left: -300px; /* set to half of the containing elements width */
    margin-top: -200px; /* set half of the containing elements height */
    transition-timing-function: cubic-bezier(0, 0, 0.5, 1);
}
<button id="toggle-button">
  Toggle Image
</button>

<div class="wrapper">
  <div class="image show" id="image-container"></div>
</div>

我创建了一个快速示例,说明它如何与 css 一起工作,仅使用 javascript 在图像元素上切换 class。

css 中的评论描述了这是如何完成的。