今天有個(gè)需求要獲得偽元素的高,但是返回卻是null坞生。就此查了下原因仔役,原來是我對偽元素沒有了解清楚。
偽元素只是在頁面顯示時(shí)起作用是己,在構(gòu)建dom樹時(shí)它被忽略又兵。
JQuery只能獲取dom節(jié)點(diǎn)。
<!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實(shí)現(xiàn)
代碼如下:
<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