简体   繁体   English

当某个 div 存在时如何隐藏元素?

[英]How to hide an element when a certain div is present?

I want to hide my sticky button when the slider or footer is being in view when scrolled upon.当滚动查看 slider 或页脚时,我想隐藏我的粘性按钮。

I tried this code:我试过这段代码:

$(window).scroll(function() {
    if ($(this).scrollTop() < 250) { 
        $("#sticky-button").css({
            'display': 'none'
        });
    }
});

So what this does is to hide my sticky button when it is below 250px scroll height.因此,它的作用是在滚动高度低于 250 像素时隐藏我的粘性按钮。

But on mobile, I realise it doesn't work as 250px in mobile is quite a huge height.但是在移动设备上,我意识到它不起作用,因为移动设备中的 250 像素是一个相当大的高度。

So how to do this by making it work upon a certain div (like: #slider, #footer) instead of setting that 250 height?那么如何通过使其在某个 div 上工作(例如:#slider、#footer)而不是设置 250 高度来做到这一点?

You should check the element for its position using .offset().top您应该使用.offset().top检查元素的 position

 $(window).scroll(function() { var elemOffsetTop = $('#slider').offset().top; if ($(this).scrollTop() > elemOffsetTop ) { $("#sticky-button").css({ 'display': 'none' }); }else{ $("#sticky-button").css({ 'display': 'block' }); } });
 #sticky-button{ position: fixed; top:0; left:0; width: 100px; height: 100px; background-color: blue; }.section{ width: 100%; height: 200px; border: 2px solid red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="sticky-button"></div> <div class="section"></div> <div class="section"></div> <div id="slider" class="section">slider</div> <div class="section"></div> <div class="section"></div> <div class="section"></div>

You can try this你可以试试这个

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

if (isScrolledIntoView($('#yourDiv'))) {
    $("#sticky-button").css({
        'display': 'none'
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM