给iframe 添加onclick事件

给iframe 添加onclick事件,第1张

首先 ,建立一个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(newthis.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 iinthis.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"),function() { alert('a click') })

内容摘抄自: https://www.cnblogs.com/limeiky/p/6632796.html

需求:

如果没有iframe,则可以通过判断点击元素的类名的方式,通过排除方法来实现。

如果iframe在本地,不存在跨域问题,还可以通过在父页面绑定方法来隐藏。

如果是跨域的,获取不到iframe的document,则还可以通过document.activeElement来实现。

调用的时候:

tips:

其实这种写法是做了个类似轮循,每隔200ms,就去判断当前页面的activeElement,如果是传入的iframe,并且hasTracked是false,就执行传入的回调函数,并把hasTracked的值置为true;

如果当前的activeElement不是iframe,就把iframe的hasTracked 置为false。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11638066.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存