jQuery slideToggle(从中间点切换)

时间:2018-01-02 13:01:34

标签: jquery css animation slidetoggle

我正在使用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">
&#13;
&#13;
&#13;

JSFiddle

2 个答案:

答案 0 :(得分:1)

作为使用jQuery动画的替代方法,您正在寻找的内容(假设我理解您所解释的内容)可以通过稍微更改DOM结构并添加几行css来完成。

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

toggleButton.addEventListener("click", () => {
    imageContainer.classList.toggle("show");
});
&#13;
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);
}
&#13;
<button id="toggle-button">
  Toggle Image
</button>

<div class="wrapper">
  <div class="image show" id="image-container"></div>
</div>
&#13;
&#13;
&#13;

我创建了一个快速示例,说明它如何使用css只能使用javascript来切换图像元素上的类。

css中的评论描述了这是如何实现的。

答案 1 :(得分:0)

使用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>