jQuery或CSS Animate - HTML元素向下移动滚动

时间:2014-05-18 15:34:23

标签: jquery css

我正在尝试设置一个时间轴,当用户向下滚动时标记会移动。我按如下方式设置了我的代码:

HTML

<div class="boxone"></div>
<div class="boxtwo"><div class="animatedcircle"></div></div>

CSS

.boxone {
  width: 400px;
  height: 4000px;
  background: red;
  float: left;
}

.boxtwo {
  width: 400px;
  height: 4000px;
  background: blue;
  border-left: 1px solid black;
  float: left;
}

.animatedcircle {
  border: 1px solid black;
  width: 25px;
  height: 25px;
  border-radius: 40px;
  position: absolute;
  right: 403px;
  top: 50px;
}

的jQuery

$(document).ready(function () {
 var el = $('.animatedcircle');
    var originalelpos = el.offset().top; // take it where it originally is on the page

    //run on scroll
    $(window).scroll(function () {
        var el = $('.animatedcircle'); // important! (local)
        var elpos = el.offset().top; // take current situation
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos + originalelpos;
        el.stop().animate({ 'top': finaldestination }, 400);
    });
});

http://codepen.io/ElaineM/pen/tIyHB

当我向下滚动时,如何动画标记向下移动?

2 个答案:

答案 0 :(得分:0)

你的意思是那个圈子?如果是,只需将.animatedcircle位置更改为固定。

答案 1 :(得分:0)

<强> DEMO

将位置更改为固定:

.animatedcircle {
  border: 1px solid black;
  width: 25px;
  height: 25px;
  border-radius: 40px;
  position: fixed;
  right: 403px;
  top: 50px;
}

然后在JS:

  $(document).ready(function () {
     var el = $('.animatedcircle');
        var originalelpos = el.offset().top; // take it where it originally is on the page
        var incrementer = 0;
        var lastScroll = 0; // used to detect scroll Up event
        //run on scroll
        $(window).scroll(function () {
            var el = $('.animatedcircle'); // important! (local)
            var elpos = el.offset().top; // take current situation
          //Sets the current scroll position
          var st = $(this).scrollTop();
          //Determines up-or-down scrolling
          if (st > lastScroll){
             //Replace this with your function call for downward-scrolling
            incrementer += 5;
          }
          else {
             //Replace this with your function call for upward-scrolling
            incrementer -= 5;
          }
          //Updates scroll position
           lastScroll = st;

            var finaldestination = originalelpos + incrementer;
            el.stop().animate({ 'top': finaldestination }, 400);
        });
    });

当你使用窗口滚动位置时,动画圆圈太过分了。所以相反,我引入了一个会慢慢增加的增量器。