【问题标题】:Height and width returning zero in hangouts环聊中的高度和宽度返回零
【发布时间】:2013-01-20 22:55:15
【问题描述】:

我正在尝试构建一个使用画布的简单环聊应用。我遇到的问题是,每当我尝试获取画布的高度和宽度时,我都会得到 0。当我在测试文件 (test.html) 中复制完全相同的代码时,一切似乎都运行良好。这是我的代码,我把所有的 css 和 html 放在一个地方,以便于阅读:

<script src="https://hangoutsapi.talkgadget.google.com/hangouts/_/api/hangout.js?v=1.2"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<div id="canvasDiv"></div>
<style>
#canvasDiv {
    width:100%;
    height:100%;
    position:relative;
}
</style>
<script>
$(window).load(function(){
    var canvasDiv = document.getElementById('canvasDiv'); 
    canvas = document.createElement('canvas');
    canvas.style.width='100%';
    canvas.style.height='100%';
    canvasDiv.appendChild(canvas);
    console.log($('#canvasDiv').height());
    canvas.width = $('#canvasDiv').width();
    canvas.height = $('#canvasDiv').height();  

在前面的代码中,console.log 在 google hangouts iframe 中打印 0,但在测试文件中打印正确的数字。

【问题讨论】:

    标签: javascript jquery google-plus hangout


    【解决方案1】:

    设置百分比充其量是不确定的。根据我的经验,我更喜欢只使用 JavaScript 函数来获取页面宽度和高度,并将 div 尺寸设置为像素,而不是百分比。

    var viewportwidth;
    var viewportheight;
    
    function resize() {
        // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
        if (typeof window.innerWidth != 'undefined') {
            viewportwidth = window.innerWidth,
            viewportheight = window.innerHeight
        }
    
        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    
        else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewportwidth = document.documentElement.clientWidth,
            viewportheight = document.documentElement.clientHeight
        }
    
        // older versions of IE
    
        else {
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportheight = document.getElementsByTagName('body')[0].clientHeight
        }
    
        canvas.style.width=viewportwidth+"px";
        canvas.style.height=viewportheight+"px";
    }
    

    此函数将获取浏览器的高度和宽度。用

    替换你的&lt;body&gt;标签
    <body onload="resize()" onresize="resize()">
    

    并且在页面加载时调用此函数,并在每次调整页面大小时再次调用(以更新&lt;div&gt; 的尺寸。)这样您将获得尺寸的实际像素,而不是百分比。

    尝试一下,如果您有问题,请告诉我。在我的编码历史中,我曾多次使用此脚本,它已成为我的最爱和最常用的脚本之一。

    【讨论】:

    • 太棒了!谢谢!它就像一个魅力。只是一个小的编辑,在为环聊实现某些内容时,您实际上无法修改 html 的主体,但您可以将函数设置为 onload 和 onresize。这也比我以前做的要好得多,因为它会调整大小。漂亮!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多