给iframe中增加点击事件并且获取点击的元素

该博客主要涉及前端开发中iframe的使用,包括设置iframe的src属性、监听iframe的加载事件,并在加载完成后对iframe内的元素进行事件绑定,特别是针对点击事件的处理。代码示例展示了如何处理浏览器的兼容性问题,确保在不同环境下都能正确监听iframe的加载完成并执行相关操作。
摘要由CSDN通过智能技术生成
<template>
  <div class="content">
    <iframe
      allowtransparency="true"
      class="iframe"
      ref="iframe"
      id="iframeId"
      :src="srcUrl"
      width="100%"
      height="100%"
      frameborder="0"
    ></iframe>
  </div>
</template>
<script>
export default {
  data() {
    return {
      srcUrl: 'xxxxxxxxxxxxxxxxx'
    }
  },
  mounted() {
    const iframe = document.querySelector('#iframeId')
    // 处理兼容行问题
    if (iframe.attachEvent) {
      iframe.attachEvent('onload',  ()=> {
        // iframe加载完毕以后执行操作
        this.getFunc()
      })
    } else {
      iframe.onload =  ()=> {
        // iframe加载完毕以后执行操作
       this.getFunc()
      }
    }
  },
  methods: {
    getFunc(){
      this.$nextTick(()=>{
        for(var i = 0; i<window.frames.length; i++) {
            window.frames[i].document.onclick = function(e) {
                console.log(e.path[0],'eeeeeeeeee')
            }
        }
        console.log( document.getElementsByTagName('a'),'iframe已加载完毕2')
       })
    },
  }
}
</script>
<style scoped>
.content {
  width: 100%;
  height: 100%;
}
.iframe {
  overflow: scroll;
}
</style>
Vue 中,由于 iframe 的内容是在独立沙箱环境中加载的,Vue 本身无法直接监听到 iframe 内部元素的事件。要解决这个问题,你需要通过一些间接的方式来实现。一种常见的做法是: 1. **通信** (Parent-Child Communication): 使用 Vue 的 `ref` 和 `v-on` 或者自定义事件 (`@custom-event`) 来在父组件和iframe子组件之间建立双向数据绑定,然后在父组件上处理点击事件。 ```vue <template> <div> <iframe ref="myIframe" @load="onIframeLoaded"></iframe> <!-- 在这里给 iframe 的 contentDocument 或 contentWindow 添加事件 --> <button @click="handleListClick">点击外部按钮</button> </div> </template> <script> export default { methods: { onIframeLoaded() { const iframeDoc = this.$refs.myIframe.contentDocument || this.$refs.myIframe.contentWindow; if (iframeDoc) { const htmlList = iframeDoc.getElementById('your-list-id'); htmlList.addEventListener('click', e => { // 触发你在 iframe 中设置的 click 事件或其他操作 this.$emit('list-item-clicked', e); }); } }, handleListClick(e) { // 在父组件中接收到子组件触发的 'list-item-clicked' 事件并处理 this.$emit('list-item-clicked', { ...e, target: e.target }); }, } } </script> ``` 2. **事件代理** (Event Delegation): 如果 iframe元素结构稳定,可以尝试在父级元素上使用事件委托来捕获点击事件,并判断是否来自 iframe。 ```javascript handleListClick(e) { if (e.target.matches('.iframe-selector')) { // 对于匹配到的iframe内的列表项,进行相应的处理 } } ``` 记住,这两种方法都需要对 iframe 内的内容有一定的控制权,并且需要考虑浏览器兼容性问题。如果iframe内容由第三方服务提供,上述方法可能不太适用。在这种情况下,你可以考虑与iframe页面的开发者合作,让他们配合提供解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值