Display live width and height values on changing window resize

核能气质少年 提交于 2019-12-05 00:16:35

问题


In html head:

<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>

In html body:

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

It works good. The question is: how can I have it to display the width/height values while resizing the browser? Like here http://quirktools.com/screenfly/ at bottom left corner.

Many thanks!


回答1:


Bind to window.onresize. Don't use document.write(). Put the <p> in your HTML and give it an id. Then just set the innerHTML of the element directly:

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



回答2:


I like gilly3's solution, but it would be useful to have the full code (for those in a hurry!)

<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>



回答3:


Or, if you're already using jquery, you can use .resize(handler) to capture the resize event and .resize() without any parameters to trigger the initial event when the window is done loading.

Like this:

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

Demo in Fiddle



来源:https://stackoverflow.com/questions/7935722/display-live-width-and-height-values-on-changing-window-resize

工具导航Map

JSON相关