简体   繁体   中英

How to implement autoscroll to follow my div

I've looked at several tutorials online and a few similar questions on SO but not been able to work out how to make the screen autoscroll left and right so that my #sheep stays in the centre of the screen.

I'm using javascript and jquery to move a simple div across the screen.

Here's my jsfiddle

http://jsfiddle.net/JosephByrne/CkkVr/

What's the best method of making the screen follow my div?

I think you're trying to move the wrong element left/right. I think you need to leave your sheep in the middle of the screen then move the background.

Something like:

var walkLeft = function() {
    $('#background').animate({left:"-=10px",top:"-=2px"}, 100);
    $('#background').animate({left:"-=10px",top:"+=2px"}, 100);
};

var walkRight = function() {
    $('#background').animate({left:"+=10px",top:"-=2px"}, 100);
    $('#background').animate({left:"+=10px",top:"+=2px"}, 100);
};

http://jsfiddle.net/CkkVr/22/ (you'll need to "jump right" to see the sheep), but you get the general idea!

You need something similar to this:

function scrollContainer() {
    var $sheep = $("#sheep");
    $("body").scrollLeft($sheep.position().left + $sheep.width());
}


That utilizes jQuery's scrollLeft() function as well as the position() function (on the sheep).


You just need to keep messing with the math until it works out properly...

I've implemented it on the "jump" functions here: http://jsfiddle.net/Dxe8a/11/

function scrollContainer() {
    var $sheep = $("#sheep");
    var $body = $("body");
    var windowWidthOver2 = ($(window).width()/2);
    var pos = $sheep.position().left + windowWidthOver2 - $sheep.width() - 80;
    if($body.width() <= (pos + windowWidthOver2 - $sheep.width() - 80)) {
        $body.width($body.width() + windowWidthOver2);
    }
    $body.scrollLeft(pos);
}

You should alter it so that it looks a bit better, but at least it follows your sheep somewhat.

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