The example in this article describes the JS method of clearing selected content. Share it with everyone for your reference. The specific analysis is as follows:
Today I was making a DIV dragging effect, and found that the text on the page would be selected when dragging, so I looked for information about JS clearing the selected content.
Found in the obtained results: In Google, Firefox, and Opera browsers, the window object has the getSelection attribute, but not in IE. The document object in IE has a selection attribute, so clearing the selected content on the page can be solved.
In Google, Firefox, and Opera browsers, we can easily clear the selected content through window.getSelection().removeAllRanges(). In IE, we can clear the selected content through document.selection.empty() .
So we can write like this:
var clearSlct= "getSelection" in window ? function(){ window.getSelection().removeAllRanges(); } : function(){ document.selection.empty(); };
"getSelection" in window is used to determine whether the window object contains the getSelection attribute. If it is true, it means that the current browser supports getSelection, that is, the browser is not an IE browser, and vice versa.
If we want to prevent users from selecting content on the page, we can do this:
//防止鼠标选中内容(当鼠标松开时清除选中内容) window.onmouseup=function(){ clearSlct(); } //防止通过键盘选中内容(当按键松开时清除选中内容) window.onkeyup=function(){ clearSlct(); } //使用jQuery的方法 $(window).on("mouseup keyup",function(){ clearSlct(); });
I hope this article will be helpful to everyone’s JavaScript programming design.