Logo 元素的内边距将为 padding: 9px 0;负载。当用户开始向下滚动页面时,我使用 animation() 将填充设置为 0px,当用户返回页面顶部时,在 jquery 中使用 animation() 再次将填充设置为 9px 0。现在的问题是当用户滚动到页面顶部时仅在几秒钟后才开始播放动画。我需要它立即发生。
http://testing.coreintegrator.com/ 这是它的演示
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
if(scroll != 0){
$('.logo').animate({padding: "0px 0px"});
} else
{
$('.logo').animate({padding: "9px 0px"});
}
});
最佳答案
发生这种情况是因为,当您滚动页面时,animate
函数会被重复调用。因此,在滚动页面时使用 animate
函数不是一个好主意。
但是,您可以使用变量来避免重复调用 animate
函数。请参见下面的示例:
$( document ).ready( function() {
var scrolled = false;
$( window ).scroll( function () {
var scroll = $( window ).scrollTop();
if ( scroll != 0 && !scrolled ){
scrolled = true;
$( '.logo' ).animate( {margin: '0'}, 'fast' );
} else if ( scroll == 0 && scrolled ) {
scrolled = false;
$( '.logo' ).animate( {margin: '9px 0'}, 'fast' );
}
})
})
body {
margin: 0;
padding-bottom: 100%
}
.logo {
display: block;
position: fixed;
margin-top: 9px;
width: 300px;
height: 100px;
background: #eee url('https://cdn1.imggmi.com/uploads/2019/2/14/01eb69be0f0914245ef9a681d6d05172-full.png') no-repeat;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-ms-background-size: 100% auto;
-o-background-size: 100% auto;
background-size: 100% auto
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='http://testing.coreintegrator.com/' class='logo'></a>
但更好的方法是,您可以使用 CSS transition
来实现。请参见下面的示例:
$( document ).ready( function() {
$( window ).scroll( function () {
var scroll = $( window ).scrollTop();
if( scroll != 0 ){
$( '.logo' ).addClass( 'scroll' )
} else {
$( '.logo' ).removeClass( 'scroll' )
}
})
})
body {
margin: 0;
padding-bottom: 100%
}
.logo {
display: block;
position: fixed;
margin-top: 9px;
width: 300px;
height: 100px;
background: #eee url('https://cdn1.imggmi.com/uploads/2019/2/14/01eb69be0f0914245ef9a681d6d05172-full.png') no-repeat;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-ms-background-size: 100% auto;
-o-background-size: 100% auto;
background-size: 100% auto;
-webkit-transition: all 100ms ease-out;
-moz-transition: all 100ms ease-out;
-o-transition: all 100ms ease-out;
transition: all 100ms ease-out
}
.scroll {
width: 150px;
height: 50px;
margin-top: 0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='http://testing.coreintegrator.com/' class='logo'></a>
注意:stop()
方法会破坏之前的所有动画,并且不会阻止滚动页面时“动画”函数的重复出现。
关于javascript - 几秒钟后 Jquery animation() 响应非常缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685342/