可能有更简单的方法可以做到这一点。但这就是我想出的。理论上,它应该可以工作:
所以要清除选择,这是其中一种方法:
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
}
}
可能有更直接的方法,但这是我能做的最好的。希望这可以帮助。