开发者

Javascript: have div always remain at the top when it reaches the top edge of browser with jquery

how to have a div that always stay on the screen?开发者_高级运维 Lets say i have a div at the left hand site. When the browser is scroll to the bottom, the div will remain there ONLY when its' top reaches the top edge of browser screen so that it will not be hidden. I am using jquery too.

Thank you.


here is a Good ScreenCast By RemySharp Regarding this Issue

http://jqueryfordesigners.com/fixed-floating-elements/

Demo Page :

http://static.jqueryfordesigners.com/demo/fixedfloat.html


You need to invoke .scrollTop() on the window and compare that with the offset top value from that DIV.

$(window).bind('scroll', function(e){
    var $div = $('.top').
        sTop = $(window).scrollTop();

    if($div.offset().top <= sTop)
        $div.css('top', sTop);
    else
        $div.css('top', '100px');
});

Whereas in this example, .top is the element which should stay at top.

Example: http://www.jsfiddle.net/2C6fB/8/


If you want it to always stay in thesame place, you can use the css property position: fixed; else you can use a combination of $(window).scroll() and .scrollTop(); to detect where your div is in relation to the screen and apply the right positioning.


/* PlugTrade.com - Sticky Top jQuery Plugin */
jQuery.fn.sticky_top = function () {
    /* check for our hidden div.. create it if it doesn't exist */
    if (!this.find("#sticky_top").length > 0)
        this.append("<div id='sticky_top' style='display:none'>"+this.css('top')+"</div>");

    var thisdiv = this;

    $(window).bind('scroll', function(e){
        var initval = thisdiv.find("#sticky_top").text();
        var wintop = $(window).scrollTop();
        var boxtop = initval.replace(/px/i, "");

        if(wintop >= boxtop)
        {
            if ( $.browser.msie ) 
            {
                thisdiv.css('top', wintop+'px');
            } else {
                thisdiv.css('position', 'fixed');
                thisdiv.css('top', '0');
            }
            // console.log(boxtop+':'+wintop);
            /* thisdiv.css('top', wintop+'px'); */
        }
        else
        {
            thisdiv.css('position', 'absolute');
            thisdiv.css('top', initval);
        }
    });
}

You can use like this:

$('#div1').sticky_top();


Keep your div position: fixed;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜