2011-05-31 80 views
16

选择我有这个功能清除在Firefox

function smth() { 
var container = null; 
var newContainer = null; 
if (window.getSelection) { // all browsers, except IE before version 9 
    alert("first if"); 
    var selectionRange = window.getSelection(); 
    if (selectionRange.rangeCount > 0) { 
     var range = selectionRange.getRangeAt(0); 
     container = range.commonAncestorContainer; 
     newContainer = container; 
    } 
} 
else { 
    if (document.selection) { // Internet Explorer 
     alert("second if"); 
     var textRange = document.selection.createRange(); 
     container = textRange.parentElement(); 
    } 
} 

if (newContainer) { 
    return newContainer.nodeName; 
} 
else { 
    alert("Container object for the selection is not available!"); 
} 
}  

后,现在我做什么,我需要选择我需要明确它做。我尝试了一些没有用的东西,有什么想法?

document.selection.clear()  

这没有工作。

回答

58

对于有问题的浏览器:

document.selection.empty() 

对于其他浏览器:

window.getSelection().removeAllRanges() 

http://help.dottoro.com/ljigixkc.php

+0

谢谢你,它有助于预期例如TinyMCE的编辑器窗口中(iframe中实际上) – Ovi 2011-05-31 12:14:37

+0

将无法​​工作。您将需要使用:tinymce.activeEditor.selection.collapse(); – Recoil 2013-12-02 06:16:57

+1

“对于有问题的浏览器”不再是这种情况。后面的选项适用于所有浏览器,包括最新版本的IE。 (假设你的意思是IE浏览器“有问题”。) – Porschiey 2014-11-07 16:47:26

0

注:如果您选择输入或textarea元素的文本,然后你如果您使用输入或textarea的标准原生html元素选择方法,代码将具有更多的跨浏览器支持。

如果使用本地选择方法选择了html输入或textarea元素,那么使用上面建议的方法在我的firefox 44.0.2上不起作用。什么对它有效,我想在所有浏览器上都能正常运行,正在运行下面的代码,它会创建一个新元素并选择它。新元素不能使用display:nonevisibility:hidden,因为在我的Firebox中未选中此元素,所以诀窍在于将所有大小属性​​强制设置为0\none以使其不可见。

var tempElement = document.createElement("input"); 
tempElement.style.cssText = "width:0!important;padding:0!important;border:0!important;margin:0!important;outline:none!important;boxShadow:none!important;"; 
document.body.appendChild(tempElement); 
tempElement.select(); 
/* Use removeChild instead of remove because remove is less supported */ 
document.body.removeChild(tempElement); 
+0

这很有效,但窃取了输入字段的焦点。 – 2016-06-24 22:46:35

+0

@LawrenceDol然后你可以重新调整输入字段后运行此,如果失去焦点是一个问题给你。 – 2016-06-26 03:05:04

0

使用 tinymce.activeEditor.selection.collapse() 如果不工作,然后用 const range = tinymce.activeEditor.dom.createRng(); tinymce.activeEditor.selection.setRng(range)