简体   繁体   中英

Javascript scroll doesn't stop

hi everyone i'm trying to do simple scroll share box widget but it doesn't work. It must stop on special div (stopscroll), but it don't stop and scrolling down until web page footer. any ideas why?

var windw = this;

$.fn.followTo = function ( elem ) {
    var $this = this,
        $window = $(windw),
        $bumper = $(elem),
        bumperPos = $bumper.offset().top,
        thisHeight = $this.outerHeight(),
        setPosition = function(){
            if ($window.scrollTop() <= (bumperPos - thisHeight)) {
                $this.css({
                    position: 'absolute',
                    top: (bumperPos - thisHeight)
                });
            } else {
                $this.css({
                    position: 'fixed',
                    top: 0
                });
            }
        };
    $window.resize(function()
    {
        bumperPos = pos.offset().top;
        thisHeight = $this.outerHeight();
        setPosition();
    });
    $window.scroll(setPosition);
    setPosition();
};

$('#share_box').followTo('#stopscroll');

but it doesn't stop on the div #stopscroll.

css file looks like that:

#share_box{
background: none repeat scroll 0% 0% #E1E1E1;
position: fixed;
width: 65px;
padding: 15px;
border-radius: 5px 0px 0px 5px;
left: 1.89%;}

any ideas? here is jsfiddle http://jsfiddle.net/NCY6x/

There are lots of syntax and variable mistakes in your code...

I have updated the fiddle with a working and simpler demo: http://jsfiddle.net/NCY6x/2/

$.fn.followTo = function ( elem ) {
    var stopper = $(elem);
    var box = this;
    $(window).on("scroll resize", function(){
        var x_distance = (stopper.offset().top- box.outerHeight());
        if($(window).scrollTop() >= x_distance){
            box.css({"position": "absolute", "top": x_distance});
        } else {
            box.css({"position": "fixed", "top": 0});
        }
    });
};

$('#share_box').followTo('#stopscroll');

Well, in your Fiddle you haven't actually loaded jQuery , and then when loaded I get an error saying pos is not defined , which I think refers to the following line:

bumperPos = pos.offset().top;

pos doesn't appear to be set anywhere

Edit:

There were some other issues with your script. See here for a version that I think works as you intend http://jsfiddle.net/R5z6j/1/

I removed the padding on the top of #stopscroll as that doesn't move the element down so the top position was always being set to 18px (see the console output)

Edit 2:

http://jsfiddle.net/R5z6j/5/ - as you'll probably actually want it this way round

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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