我真的想知道当您点击(在移动设备上)或点击(在桌面设备上)表单提交/锚点等时,是否有任何方法可以执行某项功能。并保持一段时间不使用jQuery!
function clicked() {
//set some kind of timer or so...
}
function toBeExecutedNMillisecondsAfterAnchorWasClicked() {
//do some stuff...
}
答案 0 :(得分:1)
我会做这样的事情来区分mousedown和mouseup。然后,我会使用我创建的diff变量执行if / else语句。
这是一个小提琴:: http://jsfiddle.net/mgfkdu9x/2/
<button id="element">My Button</button>
(function () {
var element = document.getElementById('element'),
start,
end;
element.onmousedown = function () {
setTimeout(function() {
if (element.onmousedown=true)
toBeExecutedNMillisecondsAfterAnchorWasClicked();
}, 5000);
};
})();
function toBeExecutedNMillisecondsAfterAnchorWasClicked() {
console.log('function start');
}
答案 1 :(得分:0)
您可以使用setTimeout功能:
function clicked() {
// Execute your function after 2000 milliseconds
setTimeout(toBeExecutedNMillisecondsAfterAnchorWasClicked, 2000);
}
答案 2 :(得分:0)
(function() {
var mouseTimer;
function mouseDown() {
mouseUp();
mouseTimer = window.setTimeout(execMouseDown,2000); //set timeout to fire in 2 seconds when the user presses mouse button down
}
function mouseUp() {
if (mouseTimer) window.clearTimeout(mouseTimer); //cancel timer when mouse button is released
div.style.backgroundColor = "#FFFFFF";
}
function execMouseDown() {
div.style.backgroundColor = "#CFCF00";
}
var div = document.getElementById("bam");
div.addEventListener("mousedown", mouseDown);
document.body.addEventListener("mouseup", mouseUp); //listen for mouse up event on body, not just the element you originally clicked on
}());
&#13;
#bam { width:100px; height: 100px; border: 1px solid black; }
&#13;
<div id="bam"> Hold mouse button for 2 seconds. </div>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
&#13;
答案 3 :(得分:0)
http://jsfiddle.net/mgfkdu9x/4/
(function() {
var mouseTimer;
function mouseDown() {
mouseUp();
mouseTimer = window.setTimeout(execMouseDown,500);
}
function mouseUp() {
if (mouseTimer) window.clearTimeout(mouseTimer);
div.style.backgroundColor = "#FFFFFF";
setTimeout(function(){
a.setAttribute("href", "google.com");
},0);
}
function execMouseDown() {
div.style.backgroundColor = "#CFCF00";
a.setAttribute("href", "javascript:void();");
}
var div = document.getElementById("div");
var a = document.getElementById("anchor");
div.addEventListener("mousedown", mouseDown);
document.body.addEventListener("mouseup", mouseUp);
}());
编辑了espacarellos代码,因此它也适用于具有href的锚点。
答案 4 :(得分:-1)
如果你不想做出默认行为,你应该阻止它,然后在你希望通过之后执行你的功能。
为了保持简单,我会这样做:
document.getElementById("yourElementId").addEventListener('click', function(event){
event.preventDefault();
setTimeout(function(){
//YOUR CODE GOES HERE
}, 2000);
});