Javascript 如何设置iframe内容的高度和宽度?

Javascript 如何设置iframe内容的高度和宽度?,javascript,angularjs,iframe,Javascript,Angularjs,Iframe,我试图通过角度设置iframe内容高度 我有点像 app.controller('testCtr' ['$scope', '$window' ), function() { var newWin = $window.open(); newWin.document.write("<iframe id='iframe' width='100%' height='100%' src='http://www.yahoo.com'></iframe>");

我试图通过角度设置iframe内容高度

我有点像

app.controller('testCtr' ['$scope', '$window' ), function() {
   var newWin = $window.open();
   newWin.document.write("<iframe id='iframe' width='100%' height='100%' 
   src='http://www.yahoo.com'></iframe>");

   var iframe = newWin.document.getElementById('iframe');
   iframe.addEventListener('load', function() {                    

       //after iframe is loaded, I want to set the hight of the contents here
       var t =  iframe.contentWindow.document.body.offsetWidth;              

       //console.log(t)  -> return undefined.   

       iframe.contentDocument.body.scrollWidth = '500px';
       iframe.contentDocument.body.scrollHeight = '500px';
   })
}])
app.controller('testCtr'['$scope','$window'),function(){
var newWin=$window.open();
newWin.document.write(“”);
var iframe=newWin.document.getElementById('iframe');
iframe.addEventListener('load',function(){
//加载iframe之后,我想在这里设置内容的高度
var t=iframe.contentWindow.document.body.offsetWidth;
//log(t)->返回未定义。
iframe.contentDocument.body.scrollWidth='500px';
iframe.contentDocument.body.scrollHeight='500px';
})
}])

我该如何做到这一点?

您面临的问题是

另外,请记住,如果你尝试iframe yahoo.com,除非你实际上是yahoo的工程师,否则你会遇到跨来源问题

我建议你阅读这篇伟大的问答,我打赌它会让你更好地理解,也许你甚至会避免在你的网站上出现iFrame的问题。

然而,如果我不举一个例子,这不是一个正确的答案。您可以使用javascript轻松设置iframe的宽度和高度,尽管CSS类更倾向于保持代码整洁

var app = angular.module('testApp', []);

app.controller('testCtrl', ['$scope', function($scope) {

    $scope.resizeMe = function() {
        var r = Math.round(Math.random() * 100) + 200;

        // For reference, this is how you get the original size:
        // $("#myIframe").height($("#myIframe").contents().find("html").height());

        $("#myIframe").width(r);
        $("#myIframe").height(r);
    };
}]);


<div ng-app="testApp">
    <div ng-controller="testCtrl">
        <button ng-click="resizeMe()">Resize!</button>
        <br>
        <iframe id="myIframe" src="http://example.com"></iframe>
    </div>
</div>
var-app=angular.module('testApp',[]);
app.controller('testCtrl',['$scope',函数($scope){
$scope.resizeMe=函数(){
var r=Math.round(Math.random()*100)+200;
//以下是获得原始尺寸的方法,仅供参考:
//$(“#myIframe”).height($(“#myIframe”).contents().find(“html”).height());
$(“#myIframe”)。宽度(r);
$(“myIframe”)。高度(r);
};
}]);
调整大小!

下面是演示: