【问题标题】:Display live width and height values on changing window resize在更改窗口大小时显示实时宽度和高度值
【发布时间】:2011-10-28 22:59:49
【问题描述】:

在html头中:

<script type="text/javascript">
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        myWidth = window.innerWidth; myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
        myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
    }
</script>

在html正文中:

<script type="text/javascript">
    document.write('<p>' + myWidth + 'x' + myHeight + '</p>');
</script>

效果很好。问题是:如何在调整浏览器大小的同时显示宽度/高度值?喜欢这里http://quirktools.com/screenfly/在左下角。

非常感谢!

【问题讨论】:

  • 这个过去的stackoverflow问题有帮助吗? stackoverflow.com/questions/641857/…
  • 我在网上找到了上面的代码。我完全是初学者。如果有人可以编写整个代码(用我上面的代码总结)那就太好了。谢谢。

标签: javascript resize


【解决方案1】:

我喜欢 gilly3 的解决方案,但拥有完整代码会很有用(对于那些赶时间的人!)

<script>
    window.onresize = displayWindowSize;
    window.onload = displayWindowSize;

    function displayWindowSize() {
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
        // your size calculation code here
        document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
    };
</script>

【讨论】:

    【解决方案2】:

    绑定到window.onresize。不要使用document.write()。将&lt;p&gt; 放入您的HTML 并为其指定一个ID。然后直接设置元素的innerHTML:

    window.onresize = displayWindowSize;
    window.onload = displayWindowSize;
    function displayWindowSize() {
        // your size calculation code here
        document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
    };
    

    【讨论】:

    • 它在调整窗口大小时效果很好,非常感谢。第一次打开页面或重新加载后如何显示它?
    【解决方案3】:

    或者,如果您已经在使用 jquery,您可以使用.resize(<i>handler</i>) 来捕获调整大小事件,并使用.resize() 不带任何参数来在窗口加载完成时触发初始事件。

    像这样:

    $(window).resize(function() {
        // your size calculation code here
        $("#dimensions").html(myWidth);
    }).resize();
    

    Demo in Fiddle

    【讨论】:

      【解决方案4】:
      <!DOCTYPE html>
      <html>
      <head>
      <title>How to get width of screen when window is resizing?</title>
      </head>
      <body>
      <script>
      window.onresize=function()
      {
          document.body.innerHTML=window.innerWidth;
      }
      </script>
      </body>
      </html>
      

      学习每一行代码的含义-https://jaischool.com/javascript-lang/how-to-get-live-width-of-window-when-it-is-resizing.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-15
        • 2021-12-24
        • 1970-01-01
        相关资源
        最近更新 更多