2015-12-08 54 views
4

選擇的亮點我在我的HTML網頁不超過兩次的I幀。首先我在iframe1中做一些文字選擇,然後移動到iframe2並做一些文字選擇。問題是,當我在iframe2中進行文本選擇時,突出顯示的背景中的突出顯示的文本應該被移除,但這不會發生。如何做到這一點如何清除裏面的iframe

<!doctype html> 
<html lang="en"> 
<head> 

</head> 
<body> 
    <iframe src="test.html"></iframe> 
    <iframe src="test2.html"></iframe> 
</body> 
</html> 

回答

0

可能有更簡單的方法來做到這一點。但這是我想出來的。從理論上講,它應該工作:

所以要明確的選擇,這是其中一個方法:

var clearSelection = function(){ 
    if (window.getSelection) { 
     if (window.getSelection().empty) { // Chrome 
      window.getSelection().empty(); 
     } else if (window.getSelection().removeAllRanges) { // Firefox 
      window.getSelection().removeAllRanges(); 
     } 
    } else if (document.selection) { // IE? 
     document.selection.empty(); 
    } 
} 

來源:Clear Text Selection with JavaScript

現在我們需要來觸發此功能除了其他所有的I幀一個已經被激活,一個被點擊的iframe,或者其中的任何文本選擇。

這需要I幀,這是稍微複雜之間的通信。

每個iframe中,把那個是這樣一個功能:

//iframe1 
document.addEventListener("click", function(){ 
window.postMessage({ 
    "source": "iframe1" 
}, "*"); 
}) 

//iframe2 
document.addEventListener("click", function(){ 
window.postMessage({ 
    "source": "iframe2" 
}, "*"); 
}) 

現在訂閱這些消息在父框架是這樣的:

//parent frame 
var childrenFrames = window.parent.frames; 
window.onmessage = function(e){ 
    if (e.data.source === "iframe1") { 
     childrenFrames[1].postMessage("clearSelection", "*"); 
    } 
    if (e.data.source === "iframe2") { 
     childrenFrames[0].postMessage("clearSelection", "*"); 
    } 

}; 

我使用到了孩子I幀的參考window.top.frames(訪問頂部窗口對象)或window.parent.frames(訪問直接父窗口對象,而有可能是其他更高級別的祖先) [來源:How do I postMessage to a sibling iFrame]

現在,再次,在孩子幀,訂閱消息「clearSelection」像這樣:

//iframe1, iframe2 
window.onmessage = function(e){ 
    if(e.data === "clearSelection"){ 
     clearSelection(); // the method I mentioned in the beginning 
    } 
} 

有可能是一個更直接的方式,但是這是我能做到的最好。希望這可以幫助。