jQuery中的show/hide div在固定位置下无法正常工作

4
使用jquery显示/隐藏
时,如果
的包装器设置为position:fixed,则无法正常工作,但是如果将其更改为position:relative,则显示/隐藏
将恢复正常工作。
这是 position:relative示例
这是position:fixed示例,其中show/hide
未显示。
var flag = 0;
var leftValue;
$('#button').on('click',function(){
      flag = !flag;
      leftValue = flag ? 100 : 0;
        $('#right').animate({ left: leftValue }, 'slow', function() {
            $('#button').text(function(i,v){
           return v == 'Close' ? 'Menu' : 'Close';
         });
        });
    });

/* show/hide DIV when passed the other div */
       $(document).scroll(function(){
       var vis = ($(document).scrollTop() > ($('.passedMe').offset().top+$('.passedMe').height()));
       $('.showHide').css('display', vis?'':'none')
       });
      /* show/hide DIV when passed the other div */

有人有想法吗...

4个回答

2
那是因为你的代码在这里。
$(document).scroll(function(){

如果您滚动文档或正文,那么您的滚动函数将起作用,但是因为您使用了fixed定位,所以在正文中没有滚动条,而滚动条

<div id="right">
    ...
</div>

这会使得滚动函数永远不会被调用,因此您需要进行更改。
$(document).scroll(function(){
    ...
});

为了

$("#right").scroll(function(){    // Depend on the container that use the position: fixed;
    ...
});

here's the Updated Fiddle


0
原因是fixed定位会自动将lefttop设置为0,而relative定位则相对于父标签设置。
设置以下CSS应该就可以解决问题:
top:20px

0
将滚动条绑定到你的 div#right
$("#right").scroll(function () {
    console.log("scrolling")
    var vis = ($(document).scrollTop() > ($('.passedMe').offset().top + $('.passedMe').height()));
     $('.showHide').css('display', vis?'':'none')
});

演示


0

我的猜测是#right{position: relative/fixed }对行为有影响。

position: fixed:元素相对于浏览器窗口定位。

position: relative:元素相对于其正常位置定位。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接