javascript 使用jquery以厘米为单位获取div的高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10794891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting height of a div in centimeter using jquery?
提问by Rosh
I'm having a div , in which I am adding data dynamically, I want to get the height of the particular div in centimeter. Because I need to control the amount of data that can be displayed in that div based on the height.
我有一个 div ,我在其中动态添加数据,我想以厘米为单位获取特定 div 的高度。因为我需要根据高度控制该div中可以显示的数据量。
回答by thecodeparadox
1px = 0.02645833 cm;
or
或者
1 cm = 37.795276px;
See these links:
请参阅这些链接:
How to access screen display's DPI settings via javascript?
回答by Jonathan Pasquier
Here is a little javascript function to convert CSS pixels to centimeters:
这是一个将 CSS 像素转换为厘米的 JavaScript 小函数:
function px2cm(px) {
var d = $("<div/>").css({ position: 'absolute', top : '-1000cm', left : '-1000cm', height : '1000cm', width : '1000cm' }).appendTo('body');
var px_per_cm = d.height() / 1000;
d.remove();
return px / px_per_cm;
}
It inserts a 1000cm x 1000cm empty <div>
into the page and then read its height in CSS pixels.
By not using magic values (as 1px = 0.02645833 cm suggested above, which only work if your screen DPI is 96) it ensures that the current screen DPI is taken into account.
它<div>
在页面中插入一个 1000cm x 1000cm 的空白,然后以 CSS 像素读取其高度。通过不使用魔法值(如上面建议的 1px = 0.02645833 cm,仅当您的屏幕 DPI 为 96 时才有效),它确保将当前屏幕 DPI 考虑在内。
As the DPI of a screen can never change, you should cache the px_per_cm
to avoid any performance hit any time you call this function
由于屏幕的 DPI 永远不会改变,因此您应该缓存它px_per_cm
以避免在调用此函数时造成任何性能下降
回答by Jamiec
First you need to decide how many DPI (Dots Per Inch) you are looking at. On a screen this is usually between 72 and 100. Lets take 72 as an example.
首先,您需要决定要查看多少 DPI(每英寸点数)。在屏幕上,这通常在 72 到 100 之间。让我们以 72 为例。
72 Dots (Pixels) per Inch.
Which is 72 Pixels per 2.54cm
So 1 cm is 28.35pixels
每英寸 72 点(像素)。
这是每
2.54 厘米72 像素所以 1 厘米是 28.35 像素
Now just get the height in pixels, and do the conversion.
现在只需获取以像素为单位的高度,然后进行转换。