[英]How to move image slider next or previous using mouse?
I'm trying to use a mouse event on a slider, what the user drags to left it will go to previous, and when drag to right it will go to next. 我正在尝试在滑块上使用鼠标事件,用户向左拖动的内容将转到上一个,而向右拖动的内容将转到下一个。
This is what I have tried so far 到目前为止,这是我尝试过的
$('#main-div').mousedown(function () {
$('#slider ul').animate({
left: 0
}, 200, function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
});
Any idea on this? 有什么想法吗?
try this in order to determine the direction of movement, and then you can execute animate. 尝试此操作以确定运动方向,然后可以执行动画。
HTML structure could be HTML结构可能是
<div id="main-div">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
and by in javascript code you can bind mousedown and mouseup methods to calculate direction (also you can calculate step size) 通过javascript代码,您可以绑定mousedown和mouseup方法来计算方向(也可以计算步长)
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir, step);
});
then you can call move method to execute sliding animation 然后您可以调用move方法来执行滑动动画
function move(dir, step) {
var $ul = $mainDiv.find('ul'),
liWidth = $ul.find('li').width();
$ul.animate({
left: '+=' + (dir * liWidth)
}, 200);
}
see my jsffidle http://jsfiddle.net/pBGGH/1/ 看到我的jsffidle http://jsfiddle.net/pBGGH/1/
Of course you should check boundaries of the ul element to prevent scroll to much. 当然,您应该检查ul元素的边界以防止滚动太多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.