长期在JavaScript?是否可以在JavaScript(或jQuery)中实现“长按”?怎么样?HTML<a href="" title="">Long press</a>JavaScript的$("a").mouseup(function(){
// Clear timeout
return false;}).mousedown(function(){
// Set timeout
return false; });
3 回答
慕村9548890
TA贡献1884条经验 获得超4个赞
没有'jQuery'魔法,只有JavaScript定时器。
var pressTimer;$("a").mouseup(function(){ clearTimeout(pressTimer); // Clear timeout return false;}).mousedown(function(){ // Set timeout pressTimer = window.setTimeout(function() { ... Your Code ...},1000); return false; });
aluckdog
TA贡献1847条经验 获得超7个赞
根据Maycow Moura的回答,我写了这个。它还确保用户不会进行右键单击,这会触发长按并在移动设备上运行。DEMO
var node = document.getElementsByTagName("p")[0];var longpress = false;var presstimer = null;var longtarget = null;var cancel = function(e) { if (presstimer !== null) { clearTimeout(presstimer); presstimer = null; } this.classList.remove("longpress");};var click = function(e) { if (presstimer !== null) { clearTimeout(presstimer); presstimer = null; } this.classList.remove("longpress"); if (longpress) { return false; } alert("press");};var start = function(e) { console.log(e); if (e.type === "click" && e.button !== 0) { return; } longpress = false; this.classList.add("longpress"); if (presstimer === null) { presstimer = setTimeout(function() { alert("long click"); longpress = true; }, 1000); } return false;};node.addEventListener("mousedown", start);node.addEventListener("touchstart", start);node.addEventListener("click", click);node.addEventListener("mouseout", cancel);node.addEventListener("touchend", cancel);node.addEventListener("touchleave", cancel);node.addEventListener("touchcancel", cancel);
您还应该使用CSS动画包含一些指标:
p { background: red; padding: 100px;}.longpress { -webkit-animation: 1s longpress; animation: 1s longpress;}@-webkit-keyframes longpress { 0%, 20% { background: red; } 100% { background: yellow; }}@keyframes longpress { 0%, 20% { background: red; } 100% { background: yellow; }}
添加回答
举报
0/150
提交
取消