我有一些JavaScript用于在用户滚动时向我的<body>
元素添加一个类:
var $body = $('body');
$(window).scroll(function() {
$body.addClass('scrolling');
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrolling');
}
});
这适用于桌面浏览器,但在iOS(可能还有其他移动设备)上,只有在触摸 release 时才会添加该类,而不是在用户第一次触摸屏幕进行滚动时添加。
如何调整此脚本以在触摸时触发此类,同时仍然可以像标准桌面用户一样正常工作?
这是一个小提琴,显示了这个脚本:http://jsfiddle.net/alecrust/AKCCH/
答案 0 :(得分:1)
您可以使用ontouchstart,ontouchmove和ontouchend来处理触摸事件。
var $body = $('body');
if ("ontouchstart" in document.documentElement)
{
$(window).bind('touchmove',function(e){
e.preventDefault();
$body.addClass('scrollingTouch');
});
$(window).bind('touchend',function(e){
e.preventDefault();
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrollingTouch');
}
});
}
else
{
$(window).scroll(function() {
$body.addClass('scrolling');
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrolling');
}
});
}
这是一个有效的jsfiddle:http://jsfiddle.net/BLrtr/
可能会有一些并发症,所以我建议你阅读this来理解它们。 此外,您可能需要检查这些3rd party libraries是否有触摸事件处理。