jQuery动画仅在动画期间更改不透明度

jQuery animate change opacity ONLY during animation

本文关键字:动画 不透明度 jQuery      更新时间:2024-01-01

我有这个jquery命令:

$('html, body').animate({
                        scrollTop: stopY,
                        opacity: '0.5'
                        }, 1000);

(其中stopY是我要停止的位置)。唯一的想法是,我希望不透明度只在滚动过程中更改为0.5,一旦我处于stopY位置,它就会回到1。

animate的选项参数中提供一个complete回调,在动画完成时将不透明度设置回1:

var options = {
    duration: 1000, 
    complete: function(){ $('html, body').css('opacity', 1) }
});
$('html, body').css('opacity', 0.5).animate({ scrollTop: stopY }, options)

可以使用.animate()start选项将目标元素opacity设置为0.promise().then();在.then()处对目标元素调用.animate()以将opacity设置为1

var stopY = 400, div = $("div");
$("html, body").animate({
  scrollTop: stopY
}, {
  duration: 1000,
  start: function() {
    div.css("opacity", 0)
  }
}).promise().then(function() {
  div.animate({
    opacity: 1
  }, 500)
})
body {
  height: 800px;
}
div {
  position: relative;
  top: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
  <div>scroll to here</div>
</body>

您当前的代码正在设置不透明度和scrollTop的动画。你需要做的是:

$("body").css("opacity",0.5);
$('html, body').animate({
          scrollTop: stopY
}, 1000, function () { 
    if ($(this).is("body")) { //Done is triggered for both html and body, so we limit it to only one of the two triggers
       $("body").css("opacity",1);
    }
});