看看this answer到类似的问题。前提是使用JQuery的bind method,它将处理程序附加到它应用于的元素的事件。绑定方法采用参数eventType,该参数是一个包含一个或多个 DOM事件的字符串。该方法还将发生事件时应执行的函数作为参数。
然后,对于移动设备(其具有触摸屏)使用触摸等价物的鼠标事件:touchstart,touchmove,touchend。
所以,你的代码更改为以下:
$(document).ready(function(){
var wrapper = $("div.reveal-visible");
wrapper.bind("mousedown touchstart", function(e){
$(this).data("sliding", true);
var offs = e.pageX - $(this).offset().left
$(this).find('div').width(offs);
});
wrapper.bind("mousemove touchmove", function(e){
if ($(this).data("sliding")) {
var offs = e.pageX - $(this).offset().left
$(this).find('div').width(offs);
}
});
$(document).bind("mouseup touchend", function(e){
wrapper.data("sliding", false);
});
});
编辑:好了,所以也没工作,这一次的原因是因为当它是一个触摸屏,我们必须得触摸点从touch event。而不是使用e.pageX
作为触摸屏,请使用e.changedTouches[0].pageX
。因此,这里的更新代码:
$(document).ready(function(){
var wrapper = $("div.reveal-visible");
wrapper.bind("mousedown touchstart", function(e){
var offs;
$(this).data("sliding", true);
if(typeof e.changedTouches === "undefined" || e.changedTouches == null){
offs = e.pageX - $(this).offset().left;
}else{
offs = e.changedTouches[0].pageX - $(this).offset().left;
}
$(this).find("div").width(offs);
});
wrapper.bind("mousemove touchmove", function(e){
if($(this).data("sliding")){
var offs;
if(typeof e.changedTouches === "undefined" || e.changedTouches == null){
offs = e.pageX - $(this).offset().left;
}else{
offs = e.changedTouches[0].pageX - $(this).offset().left;
}
$(this).find("div").width(offs);
}
});
$(document).bind("mouseup touchend", function(e){
wrapper.data("sliding", false);
});
});
编辑:因此,代码是正确的,但问题是与JQuery的Event Object。 JQuery事件对象仅支持某些类型的事件,并且不包括触摸事件。有JQuery Mobile,其中包括该库的链接应该解决您的问题。但我选择在代码中混合更多“普通”JavaScript,而不必依赖其他资源。以下代码已经过测试并且可以正常工作:
$(document).ready(function(){
var wrapper = $("div.reveal-visible");
var w = document.getElementsByClassName("reveal-visible")[0];
w.addEventListener("touchstart", start);
w.addEventListener("touchmove", move);
wrapper.bind("mousedown", start);
wrapper.bind("mousemove", move);
function start(e){
var offs;
$(this).data("sliding", true);
if(typeof e.changedTouches === "undefined" || e.changedTouches == null){
offs = e.pageX - $(this).offset().left;
}else{
offs = e.changedTouches[0].pageX - $(this).offset().left;
}
$(this).find("div").width(offs);
}
function move(e){
if($(this).data("sliding")){
var offs;
if(typeof e.changedTouches === "undefined" || e.changedTouches == null){
offs = e.pageX - $(this).offset().left;
}else{
offs = e.changedTouches[0].pageX - $(this).offset().left;
}
$(this).find("div").width(offs);
}
}
$(document).bind("mouseup touchend", function(e){
wrapper.data("sliding", false);
});
});
对Jquery绑定方法使用“touchstart”和“touchend”,而不是使用mouseup和mousedown。 – chRyNaN
或更好的是,使用它们都〜$(wrapper).bind(“mousedown touchstart”,function(){});〜 – chRyNaN
感谢您的回复,但遗憾是一个痛苦,但我怎么会把这个到我的JavaScript作为不知道要编辑什么。 :) –