Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

javascript - Any way to prevent "deselection" of highlighted text?

Highlight some text on this webpage, then click basically anywhere on the document. Your selection will disappear.

Is there a way to prevent this behavior when the user clicks on a specific element, either by CSS or Javascript?

E.g.:

var element = document.getElementById("foo");
foo.onclick = function(e){
   //some magic here that prevents deselection from occuring
}

or

foo.style.preventDeselect = "true";

Edit: Perhaps I could store the selection, then after "mouseclick" restore the selection? Is there a way to store aselection, and then reselect it?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"return false" as well as "e.preventDefault()" in onmousedown works in FF and Safari, but not IE. The only solution for IE, as far as I can tell, is to throw an error.

This works in all browsers (but causes an error in IE, since preventDefault is not a method):

//clicking the 'test' element will not deselect text.
var test = document.getElementById("test");
test.onmousedown = function(e){
  e = e || window.event;
  e.preventDefault();
}

I'd still like to do this error-free in IE, if possible

Thanks to Paolo Bergantino for the the "onmousedown" tip.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...