我试图防止链接点击发射,如果在移动时滚动时意外触摸?我从来没有尝试过这样的事情,并且无法正确工作。我现在正在桌面上测试它。 我的按钮结构类似:Jquery:<a>链接click preventDefault()不工作?
<a href="http://www.google.com">
<div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>
我试图使用preventDefault()函数来替代默认的点击行动,并检查是否有网页被滚动,或者点击允许它之前是偶然工作。检查的逻辑似乎可行,但无论我做什么,链接都可以通过点击进行导航。我认为这与链接行为被传播给子div有关,但我不确定。
下面是我的脚本,问题出在最后$('a')。click();功能。
UPDATE:
我还需要一个更好的方法只用$如果有谁知道如何做到这一点( 'A')选择。但是,如果我将选择器更改为$('a> div')并将'targetLink'更改为$(this).parent()。attr('href'),它似乎可以工作,Is there一种使用$('a')的方法只是因为我的一些按钮有更多的孩子。
//Mobile accidental scroll click fix:---
//- prevent clicked link from executing if user scrolls after mousedown, until next mousedown.
//- prevent clicked link from executing if user is still scrolling and mouse is down(for slow scrolls)
$(document).ready(function(){
var self = this,
scrolling = false,
mouseDown = false,
scrollAfterPress = false;
scrollDelay = 1500,
linkConditionCheckDelay = 700;
$(window).scroll(function() {
self.scrolling = true;
console.log('scrolling:' + self.scrolling);
clearTimeout($.data(this, "scrollCheck"));
$.data(this, "scrollCheck", setTimeout(function() {
self.scrolling = false;
console.log('scrolling:' + self.scrolling);
}, scrollDelay));
});
$(document).mousedown(function(){
self.scrollAfterPress = false;
int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
self.mouseDown = true;
console.log('mousedown:'+ self.mouseDown);
}).mouseup(function(){
clearInterval(int00);
self.mouseDown = false;
console.log('mousedown:'+ self.mouseDown);
});
function checkScrollAfterPress(){
if(self.scroll === true){
self.scrollAfterPress = true;
}
}
$('a').click(function(e){
//prevent default click event behaviour
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
window.location.href = targetLink;
}
}, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
e.stopPropagation();
e.preventDefault();
});
});
尝试返回false在你的。点击功能。即返回错误; – shrmn
返回false仍然不会阻止它。如果我将选择器更改为$('a> div'),它可以在某种程度上起作用,它只是停止工作。此外,我宁愿只使用$('a')选择器,因为我的一些按钮可能有更多的孩子。 – L457
如果在桌面上进行测试,您是否考虑到了移动触摸内置的延迟? – charlietfl