gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:52 25 4
gpt4 key购买 nike

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

检查这个 fiddle :http://jsfiddle.net/a7rhdk86/

谢谢!

最佳答案

您可以使用 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();
}

参见 http://jsfiddle.net/omahlama/mybzymp7/1/

关于javascript - 获取使用 :before and :after 合成的元素的实际高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27377700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com