Auto scroll div based on mouse position

前端 未结 2 1770
轮回少年
轮回少年 2021-02-04 21:41

I want to automatically scroll a div based on mouse position using jQuery.

If you see this fiddle here, you can see a number of images that are horizontally ordered in a

相关标签:
2条回答
  • 2021-02-04 21:46

    this should at least get you headed in the right direction.

    var parent = $('#parent');
    var img = $('img:first-child');
    
    parent.on('mousemove', function(e) {
        mouseX = e.pageX
        img.css('margin-left',-mouseX/parent.width()*100);
    
    });
    

    http://jsfiddle.net/xWcXt/4/

    0 讨论(0)
  • 2021-02-04 22:07

    A slightly different way to achieve what you need:

    jQuery(function($) {
    
      $(window).load(function() {
    
        var $gal = $("#propertyThumbnails"),
          galW = $gal.outerWidth(true),
          galSW = $gal[0].scrollWidth,
          wDiff = (galSW / galW) - 1, // widths difference ratio
          mPadd = 60, // Mousemove Padding
          damp = 20, // Mousemove response softness
          mX = 0, // Real mouse position
          mX2 = 0, // Modified mouse position
          posX = 0,
          mmAA = galW - (mPadd * 2), // The mousemove available area
          mmAAr = (galW / mmAA); // get available mousemove fidderence ratio
    
        $gal.mousemove(function(e) {
          mX = e.pageX - $(this).offset().left;
          mX2 = Math.min(Math.max(0, mX - mPadd), mmAA) * mmAAr;
        });
    
        setInterval(function() {
          posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"	
          $gal.scrollLeft(posX * wDiff);
        }, 10);
    
      });
    
    });
    #parent {
      position: relative;
      margin: 0 auto;
      width: 60%;
      height: 260px;
    }
    
    #propertyThumbnails {
      position: relative;
      overflow: hidden;
      background: #444;
      width: 100%;
      height: 262px;
      white-space: nowrap;
    }
    
    #propertyThumbnails img {
      vertical-align: middle;
      height: 100%;
      display: inline;
      margin-left: -4px;
    }
    <div id="parent">
      <div id="propertyThumbnails">
    
        <img src="//placehold.it/600x400/0bf" />
        <img src="//placehold.it/600x400/f0b" />
        <img src="//placehold.it/600x400/0fb" />
        <img src="//placehold.it/600x400/b0f" />
        <img src="//placehold.it/600x400/bf0" />
    
      </div>
    </div>
    
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    where mPadd is the area (in PX, at the left and right border zone) without any sensitivity to prevent user frustrations :)

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