今天遇到一個需求,通過iframe標籤引入其它頁面(當前頁面爲a.html,被引入頁面爲b.html),在b頁面當中,點擊一個事件之後,需要讓a頁面某個元素消失,但試了很多次,iframe事件無法添加,最終還是網友的力量強大,找到了兩個方法,如果其它網友還有更好的辦法,可以留言給我。
我找到兩個方法,我全貼下面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
#box {
width: 500px;
height: 600px;
background: #ccc;
}
</style>
<body>
<div id="box">
<iframe id="iframe_css" data-types="click" src="b.html" width="300" height="600"></iframe>
</div>
</body>
<script type="text/javascript">
//第一種給iframe添加點擊方法
/* setit()
function setit() {
if(document.all) {
document.getElementById("iframe_css").attachEvent("click", dothis);
} else {
document.getElementById("iframe_css").contentWindow.addEventListener("click", dothis, false);
}
}
function dothis() {
console.log("blurred");
}*/
/////////////////////////////////
//第二種給iframe 添加點擊方法
var IframeOnClick = {
resolution: 200,
iframes: [],
interval: null,
Iframe: function() {
this.element = arguments[0];
this.cb = arguments[1];
this.hasTracked = false;
},
track: function(element, cb) {
this.iframes.push(new this.Iframe(element, cb));
if(!this.interval) {
var _this = this;
this.interval = setInterval(function() {
_this.checkClick();
}, this.resolution);
}
},
checkClick: function() {
if(document.activeElement) {
var activeElement = document.activeElement;
for(var i in this.iframes) {
if(activeElement === this.iframes[i].element) { // user is in this Iframe
if(this.iframes[i].hasTracked == false) {
this.iframes[i].cb.apply(window, []);
this.iframes[i].hasTracked = true;
}
} else {
this.iframes[i].hasTracked = false;
}
}
}
}
};
IframeOnClick.track(document.getElementById("iframe_css"), function() {
console.log(1231231231)
});
</script>
</html>
如果有錯誤,歡迎留言指正
轉載
https://blog.csdn.net/u011151452/article/details/52353566
https://blog.csdn.net/weixin_30652491/article/details/99429325