简体   繁体   English

如何实现自动滚动以跟随我的div

[英]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. 我已经在线查看了几个教程和一些类似的问题,但是没能弄清楚如何让屏幕左右自动滚动,以便我的#sheep保持在屏幕的中心。

I'm using javascript and jquery to move a simple div across the screen. 我正在使用javascript和jquery在屏幕上移动一个简单的div。

Here's my jsfiddle 这是我的jsfiddle

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

What's the best method of making the screen follow my div? 使屏幕跟随我的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! http://jsfiddle.net/CkkVr/22/ (你需要“向右跳”才能看到羊),但是你得到了一般的想法!

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). 这利用了jQuery的scrollLeft()函数以及position()函数(在绵羊上)。


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/ 我在这里实现了“跳转”功能: 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. 你应该改变它以使它看起来好一点,但至少它会跟你的羊有所不同。

PS it works better in fiddle if you view it in "/show": http://jsfiddle.net/Dxe8a/11/show 如果你在“/ show”中查看它,它在小提琴中效果更好: http//jsfiddle.net/Dxe8a/11/show

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

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