2011-05-31 82 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)