简体   繁体   English

如何使用鼠标将图像滑块移至下一个或上一个?

[英]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.

相关问题 如何仅使用Javascript动态创建带有“上一个”和“下一个”按钮的图像-视频缩略图滑块? - How to Create Image-Video Thumbnail Slider With Previous and Next Button dynamically using Javascript only? 图像 slider 与 javascript 与下一个上一个按钮 - image slider with javascript with next previous button 使用angular的简单上一个\\下一个滑块 - Simple previous\next slider using angular 如何在“Slick”滑块中自定义“上一个”和“下一个”按钮 - How to customize 'Previous' and 'Next' buttons in 'Slick' slider 创建显示上一张和下一张图像的一部分的图像滑块 - create image slider that shows part of previous and next image 如何在我的jQuery图像和文本滑块中添加左/右箭头(下一个/上一个)功能? - How do I add Left/Right Arrow (Next/Previous) functionality to my jQuery image and text slider? 使用下一个和上一个操纵滑块 - Manipulate a slider with next and previous 如何使用JS根据鼠标位置移动图像? - How to move an image depending on mouse location using JS? 如何在图像滑块中反应显示先前的图像? - How to show previous image in react in image slider? 单击下一个/上一个图像滑块/转盘运行不流畅? - Image slider/carousel not running smoothly when click next/previous?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM