Horizontal scroll on mouseMove - wide div in smaller div with overflow:hidden (Can't get the math to work)

前端 未结 1 960
你的背包
你的背包 2021-01-31 12:14

I\'m trying to make a \"line\" of image thumbs, where it scrolls on mousemove. And I got it to work, but my problem now is that i wanted to make a \"padding\" on the sides so I

相关标签:
1条回答
  • 2021-01-31 13:16

    You script is not smooth, so I modified it completely (sorry :)
    with a really simple approach:

    $(function() {
    
      const $bl = $(".thumbs-block"),
        $th = $(".thumbs"),
        blW = $bl.outerWidth(),
        blSW = $bl.prop("scrollWidth"),
        wDiff = (blSW / blW) - 1, // widths difference ratio
        mPadd = 60, // Mousemove Padding
        damp = 20; // Mousemove response softness
    
      let posX = 0,
        mX2 = 0, // Modified mouse position
        mmAA = blW - (mPadd * 2), // The mousemove available area
        mmAAr = (blW / mmAA), // get available mousemove fidderence ratio
        itv = null;
    
      const anim = () => {
        posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"    
        $th.css({
          transform: `translateX(${-posX * wDiff}px)`
        });
      };
    
      $bl.on("mousemove", function(e) {
        const mouseX = e.pageX - $(this).prop("offsetLeft");
        mX2 = Math.min(Math.max(0, mouseX - mPadd), mmAA) * mmAAr;
      }).on("mouseenter", function(e) {
        itv = setInterval(anim, 10);
      }).on("mouseleave", function() {
        clearInterval(itv);
      });
    
    });
    .thumbs-block {
      position: relative;
      overflow: hidden;
      max-width: 100%;
    }
    
    .thumbs-block .thumbs {
      display: flex;
      flex-flow: row nowrap;
    }
    <div class="thumbs-block">
      <div class="thumbs">
        <a class="thumb"><img src="http://placehold.it/120x120/0bf&text=01" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/f0b&text=02" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/bf0&text=03" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/b0f&text=04" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/fb0&text=05" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/0fb&text=06" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/0bf&text=07" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/f0b&text=08" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/bf0&text=09" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/b0f&text=10" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/fb0&text=11" /></a>
        <a class="thumb"><img src="http://placehold.it/120x120/0fb&text=12" /></a>
      </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    0 讨论(0)
提交回复
热议问题