Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual height of elements composited using :before and :after

Is there a way to get the actual height in javascript (jquery is fine too) of an element that is drawn using :before and :after?

Checkout this fiddle: http://jsfiddle.net/a7rhdk86/

Thanks!

like image 516
Thomas K Avatar asked Dec 09 '14 11:12

Thomas K


1 Answers

You can use window.getComputedStyle to access the styles of the :before pseudo-element. See http://davidwalsh.name/pseudo-element . However, this gets the css height and width of the element, not the bounding box after the rotation transform.

Getting into hacky territory, I borrowed code from http://upshots.org/javascript/jquery-copy-style-copycss , copied all the styles from the pseudo element to an actual element, added it to the DOM and used getBoundingClientRect to get the bounding box.

var style = window.getComputedStyle(
    document.querySelector(".arrow"), ":before"
    )

var dest = {}
if (style.length) {
     for (var i = 0, l = style.length; i < l; i++) {
         prop = style[i];
         camel = prop.replace(/\-([a-z])/, camelize);
         val = style.getPropertyValue(prop);
         dest[camel] = val;
     }
 } else {
     for (prop in style) {
         camel = prop.replace(/\-([a-z])/, camelize);
         val = style.getPropertyValue(prop) || style[prop];
         dest[camel] = val;
     }
 }

var copy = $("<div />").css(dest)
copy.appendTo(".arrow")
var boundingRect = copy[0].getBoundingClientRect()
console.log(boundingRect.height)
console.log(boundingRect.width)
copy.remove()

function camelize(a, b) {
    return b.toUpperCase();
}

See http://jsfiddle.net/omahlama/mybzymp7/1/

like image 91
OlliM Avatar answered Oct 20 '22 17:10

OlliM