选择文本时阻止onClick事件 [英] Prevent onClick event when selecting text
问题描述
我遇到这个问题,我需要在点击表格单元格时显示和隐藏div。但是,我还希望人们能够在单元格中选择文本并将其复制而不隐藏信息。
I've got this problem where I need to show and hide divs when clicking on a table cell. However, I also want people to be able to select text and copy it within the cell without hiding the information.
完全可以在必要时更改设计。 :)
Totally open to changing the design if necessary. :)
这是一个演示问题的小提琴
Here's a fiddle which demonstrates the issue
http://jsfiddle.net/k61u66ek/1/
这是以下的HTML代码小提琴:
Here's the HTML code in the fiddle:
<table border=1>
<tr>
<td>
Information
</td>
<td onClick="toggleInfo()">
<div id="information" style="display:none">
More information that I want to select without hiding
</div>
<div id="clicktoshow">
Click to show info
</div>
</td>
</tr>
</table>
这是javascript:
Here's the javascript:
function toggleInfo() {
$("#clicktoshow").toggle();
$("#information").toggle();
}
非常感谢任何建议/建议!
Any suggestion/advise is much appreciated!
/ Patrik
推荐答案
一种选择是检查类型$
返回的
:选择
对象的c $ c> window.getSelection
One option is to check the type
of the Selection
object returned by window.getSelection
:
function toggleInfo() {
var selection = window.getSelection();
if(selection.type != "Range") {
$("#clicktoshow").toggle();
$("#information").toggle();
}
}
http://jsfiddle.net/k61u66ek/4/
更新
如果您要定位的浏览器未在选择中公开
object然后你可以测试所选值的长度:类型
属性
If the browser you're targeting doesn't expose a type
property on the Selection
object then you can test against the length of the selected value instead:
function toggleInfo() {
var selection = window.getSelection();
if(selection.toString().length === 0) {
$("#clicktoshow").toggle();
$("#information").toggle();
}
}
http://jsfiddle.net/k61u66ek/9/
然后可以减少到布尔检查on toString
:
which can in turn be reduced down to a bool check on toString
:
if(!selection.toString()){
http://jsfiddle.net/k61u66ek/10/
这篇关于选择文本时阻止onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!