2016-12-27 70 views
0

我正在开发一个水平图像旋转木马,我希望它在滚动时不断滚动,并在将鼠标移出时停止滚动。 JS代码使用悬停事件来检测鼠标的位置,并相应地滚动到左侧或右侧。尽管如此,我无法实现它,所以我们将不胜感激。悬停以连续滚动水平格

在此先感谢

enter image description here

JS:

$('.carousel-frame ul').on('hover', function(e) { 
    var container = $(this).parent(); 
    if ((e.pageX - this.offsetLeft) < container.width()/2) { 
    var direction = function() { 
     container.stop().animate({ 
     scrollLeft: '-=600' 
     }, 1000, 'linear', direction); 
    } 
    container.stop().animate({ 
     scrollLeft: '-=600' 
    }, 1000, 'linear', direction); 
    } else { 
    var direction = function() { 
     container.stop().animate({ 
     scrollLeft: '+=600' 
     }, 1000, 'linear', direction); 
    } 
    container.stop().animate({ 
     scrollLeft: '+=600' 
    }, 1000, 'linear', direction); 
    } 
}, function() { 
    var container = $(this).parent(); 
    container.stop(); 
}); 

CSS:

.carousel-frame { 
    width: 100%; 
    margin-bottom: 0.5em; 
    padding-bottom: 1em; 
    position: relative; 
    overflow-x: scroll; 
    white-space: nowrap; 
} 
.carousel-frame ul { 
    margin: 0; 
    padding: 0; 
    height: 100%; 
    list-style: none; 
} 
.carousel-frame li.carousel-item { 
    cursor: pointer; 
    display: inline-block; 
    margin: 0 5px 0 0; 
    padding: 0; 
} 

HTML:

<div class="carousel-frame"> 
    <ul> 
    <li class="carousel-item"> 
     <img src="http://placehold.it/200x150" /> 
    </li> 
    <li class="carousel-item"> 
     <img src="http://placehold.it/200x150" /> 
    </li> 
    <li class="carousel-item"> 
     <img src="http://placehold.it/200x150" /> 
    </li> 
    <li class="carousel-item"> 
     <img src="http://placehold.it/200x150" /> 
    </li> 
    <li class="carousel-item"> 
     <img src="http://placehold.it/200x150" /> 
    </li> 
    </ul> 
</div> 

FIDDLE:

https://jsfiddle.net/btLoenzf/1/

回答