index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<iframe src="test.html" id="test_iframe"></iframe>
</div>
eeeeeee
<div id="test">这里不是iframe</div>
<script>
function getWord(){
// 非iframe中获取文字的方法
// var word = window.getSelection?window.getSelection():document.selection.createRange().text;
// iframe中获取选中文字的方法
var word =document.getElementById("test_iframe").contentWindow.getSelection();
alert( word )
}
// document.body.addEventListener("click", getWord, false);
let x,y;
document.getElementById("test_iframe").contentWindow.onmousedown=function (event) {
x = event.pageX;
y = event.pagey;
}
document.getElementById("test_iframe").contentWindow.onmouseup=function (event) {
let new_x = event.pageX;
let new_y = event.pagey;
if(x==new_x&&y==new_y){
//执行点击事件操作
}else {
// 选中操作
getWord()
}
}
</script>
</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="iframe_div">
这是一个测试iframe
</div>
</body>
</html>