javascript:获取伪:before元素的高度 [英] javascript: get height of pseudo :before element
问题描述
我需要一个伪:before
元素的高度.听起来很容易,但我无法使它正常工作.这是我尝试过的:
I need the height of a pseudo :before
element. Sounds like a no-brainer, but I cannot get it to work. This is what I have tried:
$('.test:before').height() // --> null
和 jsfiddle 有什么建议我做错了吗?
And a jsfiddle Any suggestions what I do wrong ?
更新: .test
的高度取决于内容.我需要做的是,当高度大于伪元素时,我需要在元素的右边添加一个填充.但是,因为伪元素的高度是由CSS设置的,所以我在程序中不知道它
UPDATE: The height of .test
depends on the content. What I need to do is, when the height gets bigger than the pseudo element, I need to add a padding to the right of the element. However, because the height of the pseudo element is set by css I don't know it in my program
推荐答案
Super-late reply, but: you can use vanilla JavaScript to get pseudo-element dimensions using the getComputedStyle
method:
var testBox = document.querySelector('.test');
// Or with jQuery: testBox = $('.test').get(0); - We want the JS element, without the jQuery wrapper
var pseudoBeforeHeight = window.getComputedStyle(testBox, ':before').height; // Returns (string) "70px"
这将返回一个像素值的字符串,而不管CSS声明如何(例如 4.375rem = 70px
, 10vh = 70px
, calc(8vh +1rem)= 70px
,因此您只需执行以下操作即可获取数字(以像素为单位):
This will return a string of the pixel value, regardless of the CSS declaration (e.g. 4.375rem = 70px
, 10vh = 70px
, calc(8vh + 1rem) = 70px
, so to get the number (in pixels) you can just do:
var pseudoHeightNum = parseInt(pseudoBeforeHeight);
关于兼容性:CanIUse建议,截至2017年7月,它在所有现代浏览器中都可以正常运行(显然甚至支持IE9及更高版本):
With regards to compatibility: CanIUse suggests that, as of July 2017 it works pretty much across the in all modern browsers (apparently even with support for IE9 and above): reference.
这篇关于javascript:获取伪:before元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!