如何获取渲染的 HTML 页面的大小而不是其客户端大小?
我需要获取 HTML 页面上元素所占用的大小。
不是浏览器的客户端宽度。
由于我无法强制 html 将所有内容都包含在 div 中,因为它是用户提供的,所以我需要知道该大小。
我试图获取主体元素的大小,但无法获取。 (尝试了 .width 和 style.width 但都不起作用)
I need to get the size taken up by the elements on an HTML page.
Not the client width of the browser.
As I can't enforce the html to have everything inside a div, because it's user-provided, I need to know that size.
I tried to get the body element size but can't get it. ( tried .width and style.width but neither worked )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非您具体知道要测量哪些内容元素,并且知道它们不是像 div 那样的弹性内容元素,无论实际内容如何,都可以全宽,否则您无法执行此操作。
如果您确实知道要测量哪些元素,则可以迭代所有元素以获得它们的大小和位置,并累积一个边界矩形,该矩形是所有有趣元素的并集。但是,如果这是您不知道的任意 HTML(如您所描述的),您就无法知道您关心的内容与全宽的任意容器之间的区别,因为它自然会这样做。
例如,查看包含 div 中的自动换行文本。包含的 div 为全宽,因此它始终为全宽。包含 div 的高度可以测量,但宽度始终为全宽,并且高度仅适合该特定宽度。改变宽度和高度就会不同。
Unless you know specifically which content elements you want to measure and you KNOW that they aren't elastic content elements like a div that go full width regardless of actually content, you can't do this.
If you did know which elements you wanted to measure, you can iterate through all of them get their size and position and accumulate a bounding rect that was the union of all interesting elements. But if this is arbitrary HTML (as you described it) that you don't know, you can't know the difference between something you care about and an arbitrary container that just goes full width because it does that naturally.
Look at wordwrapping text in a containing div for example. The containing div goes full width so it will always be full width. The height of the containing div would be ok to measure, but the width would always be full width and the height would only fit that particular width. Change the width and the height would be different.
尝试使用 jQuery width() 函数 http://api.jquery.com/width/。
Try using jQuery width() function http://api.jquery.com/width/.
如果您使用像 jQuery 这样的库,这将会有所帮助...浏览器有不同的报告宽度的方式...
在 jQuery 中您可以这样做...
$("#divId").width();
并获取像素宽度。更多内容请参见 http://api.jquery.com/width
It would help if you used a library like jQuery... Browsers have different ways of reporting widths...
in jQuery you can do this...
$("#divId").width();
and get the pixel width.More in http://api.jquery.com/width