如果需要,JQuery动画下来和滚动

时间:2012-06-08 22:13:44

标签: jquery jquery-ui

但只能找到滚动解决方案。

我要做的是使用动画(左或右)在屏幕上移动一个圆圈,当然是向上/向下移动,我可以这样做。

问题在于,如果需要,我希望浏览器以圆圈向上/向下滚动,以非常流畅的方式。

这是一些简单的快速脏代码,我写的只是为了搞乱

$('#circle').animate({'left': (start)+'px'},'slow').fadeIn('slow', function(){
        $(this).animate({'left': '+='+(stopRight)+'px'}, 2000, function(){
            $(this).animate({'top': '+='+(downRight)+'px'}, 2000, function(){
                $(this).animate({'left': '-='+(leftRight)+'px'}, 2000, function(){
                });
            });
        });
    });

我在哪里/如何滚动,任何建议提示,我计划在下面获取我所拥有的代码。

1 个答案:

答案 0 :(得分:1)

这是一个有效的解决方案,基于您的动画序列:

请参阅此 working Fiddle示例!

<强> HTML

<div id="circle"></div>

CSS 在小提琴上标准化,但不相关

html, body {
  width: 100%;
  height: 100%;
}
#circle {
  width: 20px;
  height: 20px;
  background-color: #444;
  border: 1px solid #212121;
  border-radius: 10px;
  position: absolute;
  top: 300px;
  left: 300px;
}

jQuery 您需要插件.watch(),请参阅下面的链接

// initial values to your variables
var start     = 0,
    stopRight = 1000,
    downRight = 300,
    leftRight = 300;

// your code as it was
$('#circle').animate({'left': (start)+'px'},'slow').fadeIn('slow', function(){
  $(this).animate({'left': '+='+(stopRight)+'px'}, 2000, function(){
    $(this).animate({'top': '+='+(downRight)+'px'}, 2000, function(){
      $(this).animate({'left': '-='+(leftRight)+'px'}, 2000, function(){});
    });
  });
});

// the code to make it all happen!
$('#circle').watch("left,top", function() {
    $("html, body").animate({
        scrollTop  : $('#circle').offset().top,
        scrollLeft : $('#circle').offset().left,
    }, 20);
}, 100);

使用插件

jQuery CSS Property Monitoring Plug-in


这样做的目的是跟踪元素移动并操纵滚动条以使其始终可见。

jQuery .scrollTop() 获取匹配元素集中第一个元素的滚动条的当前垂直位置。

jQuery .scrollLeft() 获取匹配元素集中第一个元素的滚动条的当前水平位置。

jQuery .offset() 获取相对于文档的匹配元素集中第一个元素的当前坐标。