如何清除iframe中选择的突出显示

how to clear highlight of selection inside iframe

本文关键字:选择 显示 iframe 何清除 清除      更新时间:2023-09-26

我的html页面中有两个iframe。首先,我在iframe1中进行了一些文本选择,然后转到iframe2并进行一些文本选择。问题是,当我在iframe2中选择文本时,应该删除iframe1中突出显示的背景中突出显示文本,但这并没有发生。如何进行

    <!doctype html>
<html lang="en">
<head>
</head>
<body>
    <iframe src="test.html"></iframe>
    <iframe src="test2.html"></iframe>
</body>
</html>

有一种更简单的方法可以做到这一点。但这就是我想到的。理论上,它应该起作用:

因此,要清除选择,这是一种方法:

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();
     }
}

来源:带JavaScript 的明文选择

现在,我们需要为所有其他iframe触发此函数,除了已激活的iframe,当单击该iframe时,或在其中进行任何文本选择时。

这需要iframe之间的通信,这使它稍微复杂一些。

在每个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", "*");
    }
};

我使用window.top.frames(访问顶部窗口对象)或window.parent.frames(访问直接父窗口对象,而可能还有其他更高级别的祖先)获得了对子iframe的引用[来源:如何向兄弟iFrame发布消息]

现在,在子帧中,再次订阅消息"clearSelection",如下所示:

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

也许有一个更直接的方法,但这是我能做的最好的。希望这能有所帮助。