jQuery 如何使用jQuery以相对值获取填充或边距值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1009186/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:23:42  来源:igfitidea点击:

How to get Padding or margin value in relative value using jQuery

jquery

提问by karim79

If I have an element with CSS style like code

如果我有一个像代码这样的 CSS 样式的元素

td class="bogus" style="padding-left: 1em;"

how can I use jQuery to get padding-leftvalue as 1em instead of pixels?

我如何使用 jQuery 来获取padding-left1em 而不是像素的值?

$(".bogus").css("padding-left");

This only returns the pixels, but I want it to return what's really in the code, in this case, relative value 1em instead. How ?

这仅返回像素,但我希望它返回代码中的真正内容,在这种情况下,相对值 1em 代替。如何 ?

Thanks for any guide.

感谢您的任何指导。

  • Qu

回答by karim79

What you can do is to set the base font size (the font-size property on the <body>element) to around 62.8% (some say 62.5%):

您可以做的是将基本字体大小(<body>元素上的 font-size 属性)设置为 62.8% 左右(有人说是 62.5%):

<body style="font-size:62.5%;">

This makes the base font, or 1.0em, approximately equal to 10px. It's not exact, and changes from font to font, but generally speaking it's accurate enough. Having done that, you can use EMs and their pixel equivalents:

这使得基本字体或 1.0em 大约等于 10px。它不准确,并且随着字体的变化而变化,但总的来说它已经足够准确了。完成后,您可以使用 EM 及其像素等效项:

1.0em = 10px, 1.1em = 11px, 1.2em = 12px etc.

1.0em = 10px, 1.1em = 11px, 1.2em = 12px 等等。

So you can easily convert from pixels to EMs, by dividing by 10:

因此,您可以通过除以 10 轻松地将像素转换为 EM:

var ems = parseInt($(".bogus").css("padding-left")) / 10;