我有一个附加到表行的单击事件(可以是任何对象):
<table>
<tr class="row"><td>http://google.com</td></tr>
<tr class="row"><td>http://teslamotors.com</td></tr>
<tr class="row"><td>http://solarcity.com</td></tr>
</table>
<script>
$(document).ready(function() {
$(".row").click(function() {
var href = $(this).find("td").html();
window.location.href = href;
}
}
</script>
当我在该行上有单击事件时,一旦我开始左键单击并突出显示文本,单击事件就会在用户有机会复制/粘贴之前触发。
如何仍允许用户选择该行上的文本进行复制和粘贴?
注意:这个问题是指导性的,我将提供我自己的答案。
这比这容易得多。
var down = '';
var up = '';
$('.row td').on('mousedown', function (e) {
down = e.pageX+','+e.pageY;
}).on('mouseup', function (e) {
up = e.pageX+','+e.pageY;
if(up === down) {
window.location.href = $(this).html();
}
});
你抓住鼠标的位置向下,再次向上。 如果它们匹配,则鼠标没有移动,它应该会导致链接,如果不是,那么他们可能正在选择文本。
做了一个小提琴:http://jsfiddle.net/filever10/2fm23/
答案就在标签中。 您已捕获mousedown
和mouseup
事件。
- 首先捕获
mousedown
事件并存储状态。 - 接下来捕获
mouseup
事件并将坐标与mousedown
状态进行比较。 - 如果鼠标在事件之间明显移动,请不要处理单击。
替换上述脚本部分,如下所示:
<script>
$(document).ready(function() {
var lastMouseDownEvent = null;
// capture your last "mousedown" event and store it
$(".row").mousedown(function(event) {
console.log(event); // lets see the data in your Developer Mode log
lastMouseDownEvent = event;
});
// catch the "mouseup" event and compare the distance from "mousedown"
$(".row").mouseup(function(event) {
console.log(event);
var href = $(this).find("td").html();
switch(event.which) {
case 1: // left click
// only process left click if mousedown and mouseup occur at the same location on screen.
// NOTE: for my mom's shaky hand I added the 5 pixel allowance.
if (Math.abs(event.clientX-lastMouseDownEvent.clientX) < 5 &&
Math.abs(event.clientY-lastMouseDownEvent.clientY < 5))
window.location.href = href;
break;
}
lastMouseDownEvent = null;
});
});
</script>
如果您正在寻找快速答案。
给出指令行:
请使用鼠标选择并复制 URL。