在更改窗口大小调整时显示实时宽度和高度值
问题描述:
在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/ 一样。
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.
非常感谢!
答
绑定到 window.onresize
。不要使用 document.write()
。将< p>
放入HTML并为其指定ID。然后直接设置元素的innerHTML:
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;
};