【问题标题】:Moving element horizontally on scroll在滚动时水平移动元素
【发布时间】:2017-08-25 18:37:39
【问题描述】:

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

我无法让速度和反向滚动正常工作。有什么想法我能做什么?

$(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>

【问题讨论】:

    标签: javascript jquery css scroll


    【解决方案1】:

    只需将开始位置添加到当前滚动顶部

    编辑加入速度

    $(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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多