我有一个响应式网站,我有下面的代码,当他向下滚动时,我的窗口右侧会显示一个 div,但当他向上滚动时,div 会慢慢淡出并向右移动, 问题是有时打开有时不打开,不能保证我的div在到达某个部分时总是打开和关闭 我将如何实现这一点
注意:每次用户滚动时都会调用 testAnim,但 div 不会始终打开/关闭,是否因为可能发生太多滚动?
if(true)
{
if($('.container').css('display') == 'none' ||
$('.container').css('width') == '0px'){
testAnim();
}
} else {
if($('.container').css('display') == 'block'){
testAnimBack();
}
}
function testAnim() {
$('.container').css('display','block').promise();
$(".container").animate({ width: '21.16%',opacity:'1.0'}, 500).promise();
};
function testAnimBack() {
$(".container").animate({ width: '0px',opacity:'0'}, 500).promise().done(function(){
$('.container').css('display','none').promise();
});
}
最佳答案
在我看来,您需要在 .scroll()
jQuery 方法中调用函数:
$(window).on('scroll', function(){
if($(this).scrollTop() > 100){ // check for the specific scroll top
testAnim();
}
});
然后像这样更新您的 testAnim()
函数:
function testAnim() {
if($('.container').css('display') == 'none' ||
$('.container').css('width') == '0px'){
$('.container').css('display','block');
$(".container").stop().animate({ width: '21.16%',opacity:'1.0'}, 500);
}else if($('.container').css('display') == 'block'){
$(".container").animate({width: '0px', opacity:'0'}, 500, function(){
$(this).css('display','none');
});
}
} // end of function
这样您就不需要编写两个单独的函数。
关于javascript - 使用滚动打开和关闭 div 并在到达特定部分时淡入淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22706574/