我设置了一个滑块,这里是jsfiddler http://jsfiddle.net/zZv5B/
。如何为触摸设备启用它,我希望能够通过面板区域滑动以下一个滑动和上一个幻灯片。任何想法都会非常感激。
var currentIndex = 0;// store current pane index displayed
var ePanes = $('#slider .panel');// store panes collection
function showPane(index){// generic showPane
// hide current pane
ePanes.eq(currentIndex).stop(true, true).fadeOut();
// set current index : check in panes collection length
currentIndex = index;
if(currentIndex < 0) currentIndex = ePanes.length-1;
else if(currentIndex >= ePanes.length) currentIndex = 0;
// display pane
ePanes.eq(currentIndex).stop(true, true).fadeIn();
// menu selection
$('.nav li').removeClass('current').eq(currentIndex).addClass('current');
}
// bind ul links
$('.nav li').click(function(ev){ showPane($(this).index());});
// bind previous & next links
$('.previous').click(function(){ showPane(currentIndex-1);});
$('.next').click(function(){ showPane(currentIndex+1);});
// apply start pane
showPane(0);
答案 0 :(得分:2)
使用事件(more here)'touchstart'和'touchend'并获取起始X位置和结束x位置。然后,您可以比较两者并确定触摸/滑动的方向。
var xStart, xEnd;
$('.wrap').on('mousedown touchstart', function (e) {
//get start x position
xStart = e.pageX;
}).on('mouseup touchend', function (e) {
//get the end x position
xEnd = e.originalEvent.pageX;
if (xStart != xEnd) {
//swiped
if (xStart < xEnd) {
console.log('Right');
showPane(currentIndex + 1);
}
if (xStart > xEnd) {
console.log('Left');
showPane(currentIndex - 1);
}
}
});
示例fiddle - 不确定浏览器是如何兼容的。
或者您可以使用我的fave touch启用滑块swipejs
更新: 为了使它适用于移动设备更改xEnd = e.originalEvent.pageX根据@ User543294的评论
根据MDN文档使用e.changedTouches [0] .pageX的新fiddle示例
答案 1 :(得分:0)
我刚遇到TouchSwipe。它看起来非常好,直截了当,而且非常强大。
也许是这样的?
var swipe_obj = {
swipeLeft: function(event, direction, distance, duration, fingerCount) {
$(".next").click(); },
swipeRight: function(event, direction, distance, duration, fingerCount) {
$(".previous").click(); },
};
$(".nav li").swipe(swipe_obj);
答案 2 :(得分:0)
触摸事件发生后,许多触控设备也会触发点击。他们通常遵循类似于此的安全性:触摸发生,然后它将被触发事件“touchstart” - &gt; “touchend” - &gt; “点击”。最后点击它的地方是假的,并且对原生事件有很大的延迟。但它也有效。
所以,如果效率不在乎,请不要担心。您的滑块将按预期运行。
但如果您有兴趣获得良好的性能,我建议您直接处理本机事件。使用Modernizr dinamic测试可以做到这一点。
这是一个简单的想法:
1下载Modernizr库并将其链接到您的代码中。 2根据设备功能,在代码的第一行测试您可以预期的事件类型。一行javascript即可:
var actualEvent = (Modernizr.touch) ? 'touchstart' : 'click';
如果在onReady发生之前执行此操作,则需要额外的分数。
3将当前处理程序移到“on”表单中:
$('selector').on(actualEvent, callback)
然后,您将始终处理真实事件,而不是平板电脑和手机触发的模拟点击。因为一开始的测试可以确保“actualEvent”在触摸设备上只是“touchstart”,其余部分则“点击”。
当然,您可以通过所需的触摸事件替换“touchstar”。但我认为“触摸之星”是最适合您需求的人。