Maison > interface Web > js tutoriel > le corps du texte

原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法

高洛峰
Libérer: 2017-02-06 09:33:41
original
1672 Les gens l'ont consulté

用原生js在父页面获取iframe子页面的元素,以及在子页面获取父页面元素,这是平时经常会用到的方法,这里写一个例子来总结下:

1、父页面(demo.html),在父页面修改子页面div的背景色为灰色,原来为红色:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>demo主页面</title>
    <script type="text/javascript">
    window.onload = function(){
        var _iframe = document.getElementById(&#39;iframeId&#39;).contentWindow;
        var _div =_iframe.document.getElementById(&#39;objId&#39;);
        _div.style.backgroundColor = &#39;#ccc&#39;;
    }
     
    </script>
</head>
 
<body>
 
<div id=&#39;parDiv&#39;>父页面</div>
<iframe src="demo-iframe.html" id="iframeId" height="150" width="150"></iframe> 
</body>
</html>
Copier après la connexion

2、子页面(demo-iframe.html),在子页面修改父页面div的字体颜色为红色,原来为黑色:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>子页面demo13-iframe.html</title>
    <script type="text/javascript">
    window.onload = function(){
        var _iframe = window.parent;
        var _div =_iframe.document.getElementById(&#39;parDiv&#39;);
        _div.style.color = &#39;red&#39;;
    }
    </script>
</head>
 
<body>
    <div id=&#39;objId&#39; style=&#39;width:100px;height:100px;background-color:red;&#39;>子页面</div>
</body>
</html>
Copier après la connexion

3、效果图:

(1)没有加入js时的效果图:

原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法

(2)加入js后的效果图:

原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法

以上这篇原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

更多原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法相关文章请关注PHP中文网!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!