iframe - 如何通过悬停 iframe 动态获取 iframe 内的元素
问题描述
我需要通过将鼠标悬停在元素上来获取 iframe 内的元素,例如,如果 iframe 内的按钮可用,则意味着我需要获取按钮元素。
我使用查询选择器 (:hover) 来获取悬停的元素,但我只能从顶部文档中获取 iframe 的元素。我无法获取 iframe 中的元素。
有没有人遇到过这个?
解决方案
它受到CORS的限制(因此通常您无法通过这种方式观察 3rd 方站点中包含的小部件),但在最近的浏览器中也是可行的,您只contentWindow
需要iframe
使用elementFromPoint()
.
示例frame.html
:
<div>Test1</div>
<div>Test2</div>
<div>Test3</div>
<div>Test4</div>
<div>Test5</div>
并包含test.html
:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script>
function startup(){
frame.contentWindow.document.addEventListener("click",function(event){
frame.contentWindow.document
.elementFromPoint(event.clientX,event.clientY).innerHTML+="!";
});
}
</script>
</head>
<body onload="startup()">
<iframe id="frame" width="300" height="200" src="frame.html"></iframe>
</body>
</html>
单击 的元素,iframe
其内容将附加感叹号。
推荐阅读
- java - How do I pass a parameter to a non-static method from another class?
- php - Static classes for a singular global instance
- ruby-on-rails - 使用 Rolify 仅基于实例创建角色
- java - Subsorting without losing first sort order?
- django - 如何使用日志模块持续更新日志文件,不包括 django 服务器控制台的响应消息?
- android - Set minimum year (use to select DOB) for Datepicker dialog
- angularjs - Angular 1.5 中的 bindLabel 和 bindValue selected-multiple
- jquery - 如何为缓入出动画
- node.js - 如何与多个微服务共享猫鼬模型
- twitter-bootstrap - 有能力的日期时间选择器(引导程序)