问题
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/
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>
Here's the javascript:
function toggleInfo() {
$("#clicktoshow").toggle();
$("#information").toggle();
}
Any suggestion/advise is much appreciated!
/Patrik
回答1:
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/
Update
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/
which can in turn be reduced down to a bool check on toString
:
if(!selection.toString()) {
http://jsfiddle.net/k61u66ek/10/
回答2:
You could check if there is a selection made in the click event handler:
window.getSelection().toString();
回答3:
You can use mouseup
, mousedown
and mousemove
events to achieve this:
DEMO
var isDragging = false;
$("#clickshow")
.mousedown(function() {
isDragging = false;
})
.mousemove(function() {
isDragging = true;
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
$("#information").toggle();
$("#clicktoshow").toggle();
}
});
SOURCE
回答4:
You can check if the 'information' div is toggled :
function toggleInfo() {
if(document.getElementById('information').style.display == 'none'){
$("#clicktoshow").toggle();
$("#information").toggle();
} else {
// do nothing
}
}
Check this Fiddle
来源:https://stackoverflow.com/questions/31982407/prevent-onclick-event-when-selecting-text