简体   繁体   中英

javascript: get height of pseudo :before element

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

And a jsfiddle Any suggestions what I do wrong ?

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"

This will return a string of the pixel value, regardless of the CSS declaration (eg 4.375rem = 70px , 10vh = 70px , calc(8vh + 1rem) = 70px , so to get the number (in pixels) you can just do:

var pseudoHeightNum = parseInt(pseudoBeforeHeight);

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 .

As Paulie_D said, "Pseudo elements are not selectable by jQuery".

However, if the elements on your site are styled in the same way as they are in the JSFiddle, then the div will end up being the same height as the :before, which you CAN get the value of:

$('.test').height()

If it isn't the same, then let us know why you wish to get the height, and there may be something else you can do.

You can approach it somehow depending on your layout. If your pseudo element overflows the parent element then, the scrollWith/scrollHeight will give you the pseudo element dimensions since that properties return the overall size of the box's content, visible (scrollable) or not.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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