今天有个需求要获得伪元素的高,但是返回却是null。就此查了下原因,原来是我对伪元素没有了解清楚。
伪元素只是在页面显示时起作用,在构建dom树时它被忽略。
JQuery只能获取dom节点。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../jquery-1.10.2.min.js"></script>
</head>
<style>
.sanjiao{
position: relative;
height: 100px;
width: 100px;
border: 1px solid #333;
}
.sanjiao::before{
position: absolute;
bottom: 0;
content: "";
border-width: 12px;
border-color: red bisque greenyellow gray;
border-style: solid;
display: inline-block;
box-sizing: border-box;
height: 24px;;
}
</style>
<body>
<div class="sanjiao"></div>
<p class="cont"></p>
<script>
$(".cont").html($('.sanjiao::before').height());
</script>
</body>
</html>
image.png
由此看出,JQ只得到了document对象。
如果一定要获取伪元素的css属性,那么可以使用原生js实现
代码如下:
<script>
var ele=document.querySelector('.sanjiao');
var het = window.getComputedStyle(ele,':before').getPropertyValue('height');
console.log(het);
</script>
原生JS getComputedStyle的方法解析可参考https://www.imooc.com/article/27812