滚动时水平移动元素

时间:2017-08-25 18:37:39

标签: javascript jquery css scroll

当页面向下滚动时,尝试在屏幕上水平滚动元素。我还希望能够向上滚动并使元素处于原始位置。

我无法获得速度和反向滚动才能正常工作。任何想法我能做什么?

$(document).ready(function () {
    var $horizontal = $('.horizontal');
    var startPosition = $horizontal.position();
    var speed = 14;
    var lastScrollTop = 0;
    i=0 
    $(window).scroll(function () {
         
        var st = $(this).scrollTop();
         if (st > lastScrollTop){
             // downscroll code
           i++;
         } else {
            // upscroll code
           i--;
         }
         lastScrollTop = st;
        
        newPos = startPosition.left+(i*speed)
        
        $horizontal.css({
            'left': newPos
        });
    });
});
.container {
  min-height: 50000px;
  width: 100%;
  overflow: hidden;
}
.horizontal {
    position: fixed;
    width: 50px;
    background: url(http://www.pngpix.com/wp-content/uploads/2016/06/PNGPIX-COM-Renault-Megane-RS-Trophy-White-Car-PNG-Image.png) no-repeat center center;
    background-size: cover;
    width: 500px;
    height: 200px;
    left: 50%;
    top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="horizontal">
     
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

只需将开始位置添加到当前scrollTop

即可

已修改为包含速度

$(document).ready(function () {
    var $horizontal = $('.horizontal');
    var startPosition = $horizontal.position().left;
    var speed = 14;
    $(window).scroll(function () {
        var st = $(this).scrollTop();
        var newPos = (st * (speed/100)) + startPosition;
        $horizontal.css({
            'left': newPos
        });
    });
});
.container {
  min-height: 50000px;
  width: 100%;
  overflow: hidden;
}
.horizontal {
    position: fixed;
    width: 50px;
    background: url(http://www.pngpix.com/wp-content/uploads/2016/06/PNGPIX-COM-Renault-Megane-RS-Trophy-White-Car-PNG-Image.png) no-repeat center center;
    background-size: cover;
    width: 500px;
    height: 200px;
    left: 50%;
    top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="horizontal">
     
  </div>
</div>