获取使用 :before 和 :after 合成的元素的实际高度

Tho*_*s K 6 javascript jquery

有没有办法在使用:beforeand绘制的元素的javascript(jquery也很好)中获取实际高度:after

结帐这个小提琴:http : //jsfiddle.net/a7rhdk86/

谢谢!

Oll*_*liM 5

您可以使用window.getComputedStyle:before 伪元素访问样式。请参阅http://davidwalsh.name/pseudo-element。但是,这获取的是元素的 css 高度和宽度,而不是旋转变换后的边界框。

进入 hacky 领域,我从http://upshots.org/javascript/jquery-copy-style-copycss借用了代码,将所有样式从伪元素复制到实际元素,将其添加到 DOM 并使用getBoundingClientRect获取边界框。

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();
}
Run Code Online (Sandbox Code Playgroud)

请参阅http://jsfiddle.net/omahlama/mybzymp7/1/