在更改窗口大小时显示实时宽度和高度值
在 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>
在 html body 中:
<script type="text/javascript">
document.write('<p>' + myWidth + 'x' + myHeight + '</p>');
</script>
效果很好。问题是:如何让它在调整浏览器大小时显示宽度/高度值?就像左下角的 http://quirktools.com/screenfly/ 一样。
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(4)
我喜欢 gilly3 的解决方案,但拥有完整的代码会很有用(对于那些赶时间的人!)
I like gilly3's solution, but it would be useful to have the full code (for those in a hurry!)
绑定到
window.onresize
。不要使用document.write()
。将放入 HTML 中并为其指定一个 id。然后直接设置元素的innerHTML即可:
Bind to
window.onresize
. Don't usedocument.write()
. Put the<p>
in your HTML and give it an id. Then just set the innerHTML of the element directly:或者,如果您已经在使用 jquery,则可以使用
.resize(handler)
捕获调整大小事件和.resize()
不带任何参数在窗口加载完成时触发初始事件。像这样:
Fiddle 中的演示
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:
Demo in Fiddle
要了解代码每一行的含义 - https://jaischool.com/javascript-lang/how-to-get-live-width-of-window-when-it-is-resizing.html
To learn the meaning of the each line of the code - https://jaischool.com/javascript-lang/how-to-get-live-width-of-window-when-it-is-resizing.html