2012-05-22 96 views
0

我怎樣才能水平滾動ul使用鼠標光標?基本上我想模仿this圖片庫的底部部分。我在網上找到了一種javascript方法,但並沒有那麼順利。

水平滾動ul與鼠標

+0

謝謝阿龍,你的方法,正是我一直在尋找。 – thejmazz

回答

2
<div> 
    <ul> 
     <li></li> 
     ... 
    </ul> 
</div> 

和JavaScript:

var $div = $('div'); 
var $ul = $('ul'); 

// width of div 
var width = $div.width(); 

// width of ul - width of div 
var ulWidth = $ul.width() - width; 

$div 
    .on('mouseenter', function(e) { 
     // get left offset of div on page 
     var divLeft = $div.offset().left; 

     $(window).on('mousemove', function(e) { 
      var left = e.pageX - divLeft; 
      // get percent of width the mouse position is at 
      var percent = left/width; 

      // set margin-left on ul to achieve a 'scroll' effect 
      $ul.css('margin-left', -(percent * ulWidth)); 
     }); 
    }) 
    .on('mouseleave', function() { 
     // remove mousemove event 
     $(window).off('mousemove'); 
    }) 
;​ 

http://jsfiddle.net/aarongloege/gQyz6/

你基本上需要基於鼠標位置的比例從視口的左側(DIV在UI元素放置我的例)。