簡體   English   中英

滾動方向

[英]Scroll Direction

嘗試使用鼠標滾動使 div 沿與從右上角到左下角滾動的相反方向移動。

現在它從左下角到右上角

#block {
position: absolute;
top: 400px;
left: 100px;



<script>
$(function(){
    var lastScrollYPos = 0;
    $(window).on('scroll', function(){
        var $this = $(this),
            $block = $('#block'),
            // retrieves the top and left coordinates
            position = $block.offset(),
            // X and Y factors allows to change the diagonal movement direction and
            // degree. Negative values inverts the direction.
            factorX = 1,
            factorY = 1,
            // retrieves current vertical scrolling position and calculate the
            // relative offset
            scrollYPos = $this.scrollTop(),
            offset = Math.abs(scrollYPos - lastScrollYPos),
            // mouse wheel delta is inverted respect to the direction, so we need to
            // normalize it against the direction
            direction = scrollYPos > lastScrollYPos ? -1 : 1,
            // calculates the new position. NOTE: if integers only are used for factors,
            // then `Math.floor()` isn't required.
            newTop = position.top + Math.floor(direction * offset * factorY),
            newLeft = position.left - Math.floor(direction * offset * factorX);

        // moves the block
        $block.offset({ top: newTop, left: newLeft });
        lastScrollYPos = scrollYPos;
    });
});
  </script>

我通過反轉方向(如評論中所述)然后添加最后一個 Y 位置而不是減去它來翻轉它(我已經評論過)

 $(function() { var lastScrollYPos = 0; $(window).on('scroll', function() { var $this = $(this), $block = $('#block'), // retrieves the top and left coordinates position = $block.offset(), // X and Y factors allows to change the diagonal movement direction and // degree. Negative values inverts the direction. factorX = -1, factorY = -1, // retrieves current vertical scrolling position and calculate the // relative offset scrollYPos = $this.scrollTop(), // ---- Flip around the offset calculation offset = Math.abs(scrollYPos + lastScrollYPos), // mouse wheel delta is inverted respect to the direction, so we need to // normalize it against the direction direction = scrollYPos > lastScrollYPos ? -1 : 1, // calculates the new position. NOTE: if integers only are used for factors, // then `Math.floor()` isn't required. newTop = position.top + Math.floor(direction * offset * factorY), newLeft = position.left - Math.floor(direction * offset * factorX); // moves the block $block.offset({ top: newTop, left: newLeft }); lastScrollYPos = scrollYPos; }); });
 .body { height: 1500px; width: 1000px; } #block { height: 750px; width: 500px; background: blue; position: absolute; top: -700px; left: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="body"> <div id="block"></div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM