【问题标题】:how to clear highlight of selection inside iframe如何清除iframe内的选择突出显示
【发布时间】:2016-03-12 21:58:42
【问题描述】:

我的 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>

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

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

    所以要清除选择,这是其中一种方法:

    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

    现在我们需要为所有其他 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 的引用 [来源: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
        }
    }
    

    可能有更直接的方法,但这是我能做的最好的。希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 2021-05-03
      • 1970-01-01
      相关资源
      最近更新 更多