美文网首页Web前端之路
iframe监听鼠标点击事件

iframe监听鼠标点击事件

作者: 唯爱述虞谁 | 来源:发表于2017-10-09 10:34 被阅读179次

需要实现的页面逻辑是:

1. 点击父窗体中按钮,显示侧边栏;

2. 点击页面其他区域(iframe)可以隐藏侧边栏

先构造页面文档结构:

<html>

<body>

      <aside id="sidebar">

              <%--这是需要隐藏的侧边栏--%>

     </aside>

    <button>  <%--点击按钮显示侧边栏--%> </button>

    <iframe  id="my-iframe">

      <%--获取此区域的点击事件--%>

   </oframe>

</body>

</html>

因为相对于父窗体,iframe中加载的是一个相对独立的document文档,如果直接在父窗体中使用iframe.onlick监听该区域的点击事件,则不会返回任何结果。

首先我们需要获取iframe所属的document对象:

document.getElementById('my-iframe').contentDocument

随后对这个document对象注册事件处理程序,监听响应鼠标点击事件:

document.getElementById('my-iframe').contentDocument.onclick =function(){varsidebar =        document.getElementById('sidebar');if(sidebar.style.display =='block')  sidebar.style.display ='none';

};

但是这样做还不能满足要求,因为iframe中内容会单独加载,如果我们在它的DOM解析完成之前就去获取document对象并绑定事件监听程序,将不会有任何效果。

所以我们需要先监听iframe页面加载完成事件,在处理程序中获取文档对象:

variframe = document.getElementById('my-iframe');

      iframe.onload =function(){iframe.contentDocument.onclick =function(){varsidebar =      document.getElementById('sidebar');if(sidebar.style.display =='block')  sidebar.style.display ='none';

    };

}

相关文章

网友评论

    本文标题:iframe监听鼠标点击事件

    本文链接:https://www.haomeiwen.com/subject/zkmuyxtx.html