![](/img/trans.png)
[英]Preventing default context menu on longpress / longclick in mobile Safari (iPad / iPhone)
[英]Longpress / longclick event support / plugin in jQuery
我正在一个需要鼠标悬停菜单的网站上工作。 我不建议从可访问性的角度看鼠标悬停菜单,但使用jQuery实现起来相当容易。
问题是:我们还需要支持触摸屏设备(平板电脑)。 在这样的设备上,您没有鼠标,因此鼠标悬停事件不起作用。 我希望jQuery有一个longpress事件,但事实并非如此。 我确实找到了一个使用谷歌的jQuery longclick插件 ,但它适用于jQuery 1.4,所以我并不热衷于使用它。 此外,jQuery插件网站目前正在维护,所以这不是很有帮助。
所以问题是:是否有一个优雅的jQuery 1.7 / 1.8插件来支持longpress / longclick事件?
事实证明,您可以使用jQuery 1.8的jQuery 1.4现有的longclick插件 。
$("#area").mousedown(function(){ $("#result").html("Waiting for it..."); }); $("#area").longclick(500, function(){ $("#result").html("You longclicked. Nice!"); }); $("#area").click(function(){ $("#result").html("You clicked. Bummer."); });
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script src="http://rawgit.com/pisi/Longclick/master/jquery.longclick-min.js"></script> <p id="area">Click me!</p> <p id="result">You didn't click yet.</p>
您可以做的事情是在各种鼠标事件期间使用setTimeout
延迟检查。 合并jQuery的$.data()
来跨事件(在每个元素上)存储超时应该可以帮助您完成所有操作。 这是一个例子:
HTML:
<ul id="menu">
<li><a href="#" onclick="return false;" class="test"></a></li>
<li><a href="#" onclick="return false;" class="test"></a></li>
</ul>
JS:
var mousepress_time = 1000; // Maybe hardcode this value in setTimeout
var orig_message = "Click Here"; // Remove this line
var held_message = "Down"; // Remove this line
$(document).ready(function () {
$(".test")
.html(orig_message) // Remove this line
.on("mousedown", function () {
console.log("#########mousedown"); // Remove this line
var $this = $(this);
$(this).data("checkdown", setTimeout(function () {
// Add your code to run
$this.html(held_message); // Remove this line
}, mousepress_time));
}).on("mouseup", function () {
clearTimeout($(this).data("checkdown"));
console.log("#######mouseup"); // Remove this line
$(this).html(orig_message); // Remove this line
}).on("mouseout", function () {
clearTimeout($(this).data("checkdown"));
console.log("#######mouseout"); // Remove this line
$(this).html(orig_message); // Remove this line
});
});
演示 : http : //jsfiddle.net/7jKYa/10/
还有更多与此相关的事情,因为你也在整合悬停,但在大多数情况下,我认为这可以做你想要的。
如果有必要,它可以很容易地转换为插件,否则我认为它可以单独工作。 我希望这会有所帮助!
你可以计时。
function onImageMouseDown(e){
var d = new Date();
md_time = d.getTime(); // Milliseconds since 1 Apr 1970
}
function onImageMouseUp(e){
var d = new Date();
var long_click = (d.getTime()-md_time)>1000;
if (long_click){
// Click lasted longer than 1s (1000ms)
}else{
// Click lasted less than 1s
}
md_time = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.