在 JQuery 中测试元素是否位于屏幕顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7543718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:59:04  来源:igfitidea点击:

Test in JQuery if an element is at the top of screen

jquery

提问by sir_thursday

I have a divthat is positioned about 100px from the top of the browser window. When the user scrolls down, I want the divto stay where it is untilit reaches the top of the screen. Then, I'll change some CSS with JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this divis at the top of the screen?

我有一个div距浏览器窗口顶部约 100 像素的位置。当用户向下滚动时,我希望div它停留在原处,直到它到达屏幕顶部。然后,我将使用 JQuery 更改一些 CSS 以将位置更改为固定并将边距顶部更改为 0。如果这div是在屏幕顶部,我如何在 JQuery 中进行测试?

回答by Joseph Silber

var distance = $('div').offset().top,
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
        // Your div has reached the top
    }
});

P.S.For better performance, you should probably throttle the scroll event handler.
Check out John Resig's article: Learning from Twitter.

PS为了获得更好的性能,您可能应该限制滚动事件处理程序。
查看 John Resig 的文章:从 Twitter 学习

回答by Josh

hey you can do like this :

嘿,你可以这样做:

var distance = $('.yourclass').offset().top;

$(window).scroll(function() {
    if ( $(this).scrollTop() >= distance ) {
        console.log('is in top');
    } else {
        console.log('is not in top');
    }
});

回答by Damon

Not so much an answer, but could be helpful to someone else. Using the accepted answer above and also referencing the 'Learning from Twitter' link (thank you @Joseph Sibler) I came up with the following.

不是一个答案,但可能对其他人有帮助。使用上面接受的答案并参考“从 Twitter 学习”链接(谢谢@Joseph Sibler),我想出了以下内容。

I am using a Twitter Bootstrap Navbarfor my primary navigation. It has an ID of megamenu.

我使用Twitter Bootstrap Navbar作为我的主要导航。它的 ID 为megamenu

I also have a 'login' button on my page that when clicked, slides the navbar and all contents below it down to reveal the login form. So what? Well, now the position of my navbar has changed and if I don't update that position, when I scroll the navbar will fly up to the top of the browser - even though it's not really at the top.

我的页面上还有一个“登录”按钮,单击该按钮时,会将导航栏及其下方的所有内容向下滑动以显示登录表单。所以呢?好吧,现在我的导航栏的位置已经改变,如果我不更新那个位置,当我滚动导航栏时,导航栏会飞到浏览器的顶部——即使它不是真的在顶部。

I came up with this to update the navbar position so if a user clicks 'login' and then scrolls, the navbar will correctly fix itself to the top.

我想出这个来更新导航栏的位置,所以如果用户点击“登录”然后滚动,导航栏将正确地固定到顶部。

logincollapseis my container div that holds the login form and other hidden content until the loginbutton is clicked.

logincollapse是我的容器 div,它保存登录表单和其他隐藏内容,直到login单击按钮。

I'm sure there is room for improvement - so please correct me, I'll update accordingly.

我确定还有改进的空间 - 所以请纠正我,我会相应地更新。

jquery

查询

var did_scroll = false,
    $window = $(window),
    megamenu_distance = $('#megamenu').offset().top; // The default position of the navbar

$('#logincollapse').slideToggle(300, 'easeInOutQuint', function () {
    megamenu_distance = $('#megamenu').position().top; // Updated position of the navbar
    ....
});

$window.scroll(function (event) {
    did_scroll = true;
});

setInterval(function () {
    if (did_scroll)
    {
        did_scroll = false;

        if ($window.scrollTop() >= megamenu_distance)
        {
            $('#megamenu').addClass('navbar-fixed-top');
        }
        else
        {
            $('#megamenu').removeClass('navbar-fixed-top');
        }
    }
}, 250);

回答by mlibre

when you have header. and then aside bar. for fixing aside bar, when it is at top of the screen:

当你有标题时。然后放在一边吧。用于固定边栏,当它位于屏幕顶部时:

Javascript:

Javascript:

var scroll_happened = false;
var aside_from_top = $('aside').offset().top;
$window = $(window);

$window.scroll(function()
{
    scroll_happened = true;
});

setInterval(function()
{
    if(scroll_happened == true)
    {
        scroll_happened = false;
        if($window.scrollTop() >= aside_from_top)
        {
            $('#aside_container').addClass('fixed_aside');
        }
        else
        {
            $('#aside_container').removeClass('fixed_aside');
        }
    }
} , 250);

Css:

css:

.fixed_aside
{
    position: fixed;
    top: 0;
    bottom: 0;
}

Html:

网址:

<aside>
    <div id="aside_container">
        <section>
        </section>
        <section>
        </section>
        <section>
        </section>
    </div>
</aside>

回答by user8197823

    $(document).ready(function(){  
    var $doc           = $(document);
    var position       = 0;
    var top = $doc.scrollTop();         // ?? ???? ??  
    var screenSize     = 0;             // ????  
    var halfScreenSize = 0;             // ??? ?  

    /* ??? ?? ? ?? */  
    var pageWidth      = 1000;          // ??? ?, ??:px  
    var leftOffet      = 409;           // ????? ?(?? -, ??? +), ??:px  
    var leftMargin     = 909;           // ??? ??? ??? ??? ??, ??:px, leftOffet? pageWidth? ??? ??? ??.  
    var speed          = 1500;          // ???? ?? : "slow", "normal", or "fast" or numeric(??:msec)  
    var easing         = 'swing';       // ????? ?? ?? ??? linear, swing  
    var $layer         = $('#quick');   // ??? ???  
    var layerTopOffset = 140;           // ??? ?? ???, ??:px  
    $layer.css('z-index', 10);          // ??? z-???  
    /* ??? ?? ? ? */

    // ?? ?? ???? ?? ??  
    function resetXPosition()  
    {  
        $screenSize = $('#contact').width();            // ????  
        halfScreenSize = $screenSize / 2;               // ??? ? 
        xPosition = halfScreenSize + leftOffet;  
        if ($screenSize < pageWidth)
            xPosition = leftMargin;
        $layer.css('left', xPosition);  
    }  


    // ??? ?? ?? ???? ???? ?? ??? ??  
    if (top > 0 )  
        $doc.scrollTop(layerTopOffset+top);  
    else  
        $doc.scrollTop(0);  

    // ?? ???? ?? ?? ??  
    $layer.css('top',layerTopOffset);  
    resetXPosition();  

    // ??? ?? ?? ???? ????  
    $(window).resize(resetXPosition);  

    // ??????? ????  
    $(window).scroll(function(){  
        yPosition = $doc.scrollTop() + layerTopOffset;  
        $layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false});  
    });  
});