日期:2014-05-16  浏览次数:20394 次

js访问iframe里面DOM

解决一个让iframe的高度自适应src文件的高度,提供两种解决方法:

?

main.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>main</title>
<script>   
    //方法1
    var iframe_inner = function( h ){
        document.getElementById('frame').height = h;
        alert("方法1---" + h);
    }
    //方法2
    window.onload = function(){
        var iObj = document.getElementById('frame');
        var height =  iObj.contentWindow.document.documentElement.scrollHeight;
        iObj.height = height;
        alert("方法2---" + height);
    };
</script>
</head>
<body>
    <iframe src="src.html" id="frame" />
</body>
</html>
?

src.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>src</title>
<script>
    window.onload = function(){
        parent.iframe_inner(document.documentElement.scrollHeight);
    }        
</script>
</head>
<body style="height:300px;">
</body>
</html>
?

?