如何在页面中获取iframe中的某个元素

场景:在首页中,用iframe引用头部
目的:在首页中获取iframe中的登录class或id
实现:用jqeury实现 点击登录弹出登陆注册框显示 / 点击X登录注册框和遮罩层隐藏
在这里插入图片描述
//页面iframe引入

<iframe src="/登录表单弹窗.html" id="ddl"  frameborder="0" scrolling="no" style="position: absolute; width:100%; display: none; height: 5500px;"></iframe>
    <iframe src="/网页头部.html" id="myIframe" name="ifm" frameborder="0" scrolling="no" style="width:100%; height: 148px;"></iframe>
  

第一种方法:(建议封装起来)

jqeury写


$(function () {
 var headerIframe = $('#myIframe');
if (headerIframe.length > 0) {
      // 等待iframe加载完成
 headerIframe.on('load', function() {
         // 获取iframe内部文档
         var contentDoc = headerIframe[0].contentDocument || headerIframe[0].contentWindow.document;
         // 获取指定的元素
          $(contentDoc).find('#dl').click(function(){
               //遮罩层和登录
              $("#ddl").show();
          })
    });
 }
 })

第二种方法:(建议封装起来)
jqeury写


$(function () {
//等待 iframe加载过程
$("#myIframe").on("load",function(){
// 在iframe中找到登录的id
   $("#myIframe").contents().find('#dl').click(function(){
   //想要实现的样式
      $("#ddl").show();
      //找到
      $("#ddl").contents().find('.X').click(function(){
         $("#ddl").hide()
 
       })
   })
})
})
  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在HTML,`iframe`用于嵌入另一个网页内容。如果你想要在`iframe`加载完成后获取其高度,你可以使用`onload`事件和JavaScript。以下是一个简单的示例: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>IFrame Height Example</title> </head> <body> <div id="container"> <iframe id="myIframe" src="https://example.com" style="display:none;"></iframe> </div> <script> // 获取iframe元素 var iframe = document.getElementById("myIframe"); // 当iframe完成加载时触发 iframe.onload = function() { // 获取iframe的实际高度 var iframeHeight = iframe.contentWindow.document.body.offsetHeight; // 或者使用innerHeight属性(包括滚动条的高度) // var iframeHeight = iframe.contentWindow.document.documentElement.offsetHeight; // 更新或使用这个高度值 console.log('IFrame height is:', iframeHeight); // 在这里你可以将iframe高度设置到某个元素或者执行其他操作 document.getElementById("container").style.height = iframeHeight + 'px'; }; </script> </body> </html> ``` 在这个例子,`onload`事件会在`iframe`的内容完全加载后被触发。然后,你可以通过`contentWindow`属性获取`iframe`加载的内容页面的window对象,进而获取`body`或`documentElement`的高度。 相关问题-- 1. `onload`事件在JavaScript是什么意思? 2. 为什么要使用`contentWindow`而不是直接获取`iframe`的height属性? 3. 如何处理跨域情况下iframe的`onload`事件?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值