简体   繁体   English

如何在node.js中找到HTML元素的高度?

[英]How to find height of a HTML element in node.js?

I am stuck with quite a tricky issue for a couple of days now. 几天以来,我一直遇到一个棘手的问题。 I have a auto-generated HTML page in a variable as string in node.js . 我有一个自动生成的HTML页面,该页面的变量为node.js字符串。 I need to find the height of some HTML elements and do HTML manipulations (like tag creation, deletion, append, css attribute setting etc). 我需要找到一些HTML元素的高度并进行HTML操作(例如标签创建,删除,附加,css属性设置等)。

Obviously I need to make a DOM like structure of my HTML page first and then proceed. 显然,我需要先创建HTML页面的类似于DOM的结构,然后继续。

While for the HTML manipulations I have many options like cheerio , node.io , jsdom etc but none of these allow me to find the height of the element at the node. 虽然对于HTML操作,我有很多选项,例如cheerionode.iojsdom等,但是这些都不能让我找到节点上元素的高度。

So after wasting quite a lot of time on it, I have decided to look for heavier solutions, something like implementing a headless browser ( phantomjs etc.) at the node and drive an elements offsetHeight through plain javascript. 因此,在浪费大量时间之后,我决定寻找更重的解决方案,例如在节点上实现无头浏览器( phantomjs等),并通过普通的javascript驱动元素offsetHeight

Can anyone tell me if it is possible to reach my objective like this? 谁能告诉我是否有可能达到我的目标? What headless browser will be best suited for this task? 哪种无头浏览器最适合此任务?

If i am going in the wrong direction, then can anyone suggest me any other working solution? 如果我走错了方向,那么有人可以建议我其他可行的解决方案吗?

At this point I am ready to try anything. 此时,我准备尝试任何东西。

Thnx in advance!! 提前thnx!

Note: Using javascript at the client side has many problems in my particular case because the contents of the generated HTML page are supposed to be used by the client to paste in his website. 注意:在我的特定情况下,在客户端使用javascript有很多问题,因为客户端应该使用生成的HTML页面的内容粘贴到他的网站中。 Leaving a running javascript that re-structures the HTML will make it difficult at his end. 留下运行中的javascript来重新构造HTML,将使他的工作陷入困境。

Node's server-side HTML libraries (like cheerio and jsdom) are strictly DOM API emulation libraries. Node的服务器端HTML库(例如cheerio和jsdom)严格来说是DOM API仿真库。 They do not attempt to actually render a document, which is necessary to compute element size and position. 他们没有尝试实际渲染文档,这对于计算元素的大小和位置是必需的。

If you really need to calculate the size of an element on the server, you need a headless browser like PhantomJS . 如果您确实需要计算服务器上元素的大小,则需要像PhantomJS这样的无头浏览器。 It is a full WebKit renderer with a JavaScript API. 它是带有JavaScript API的完整WebKit渲染器。 It is entirely separate from node, so you either need to write a utility script using Phantom's API , or use a npm module that lets you control Phantom from node . 它与node完全分开,因此您需要使用Phantom的API编写实用程序脚本,或者使用npm模块让您从node控制Phantom


After reading the comments under your question, it is pretty clear that you should not be calculating heights on the server. 阅读问题下的注释后,很明显您不应该在服务器上计算高度。 Client-side code is the proper place to do it. 客户端代码是执行此操作的适当位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM