1、用js获取伪元素属性
<style> .pie { width: 200px; height: 200px; background-color: aqua; } .pie::before { content: '我是你爸爸'; color: blue; background-color: red; } </style> <div class="pie"></div> <script> let color = window.getComputedStyle(document.querySelector('.pie'), ':before').getPropertyValue('color') let bgColor = window.getComputedStyle(document.querySelector('.pie'), ':before').getPropertyValue('background-color') console.log(color, bgColor) // rgb(0, 0, 255) rgb(255, 0, 0) let content = window.getComputedStyle(document.querySelector('.pie'), ':before').getPropertyValue('content') console.log(content) // "我是你爸爸" </sciprt>
2、classList属性
<div class="pie"></div> <script> let pie = document.querySelector('.pie') pie.classList.add('a1') // pie a1 添加一个类 pie.classList.add('b1', 'b2', 'b3') // pie a1 b1 b2 b3 添加多个类 pie.classList.remove('a1', 'b2') // pie b1 b3 删除多个类或者一个类 pie.classList.toggle('aaa') // pie b1 b3 aaa 切换类,如果没有aaa类,则添加aaa类 pie.classList.toggle('ccc') // pie b1 b3 aaa ccc 没有ccc就添加ccc pie.classList.toggle('ccc') // pie b1 b3 aaa 有ccc类就删除ccc let flag = pie.classList.contains('aaa') let flag1 = pie.classList.contains('aaa1') console.log(flag, flag1) // true false 判断有没有该类 console.log(pie.classList) // ["pie", "b1", "b3", "aaa", value: "pie b1 b3 aaa"] 获取的类名组成一个数组 console.log(pie.classList.length) // 4 console.log(pie.classList.value) // pie b1 b3 aaa </script>
classList目前兼容到ie10,ie9及以下的兼容:
if (!("classList" in document.documentElement)) { Object.defineProperty(HTMLElement.prototype, 'classList', { get: function() { var self = this; function update(fn) { return function(value) { var classes = self.className.split(/\s+/g), index = classes.indexOf(value); fn(classes, index, value); self.className = classes.join(" "); } } return { add: update(function(classes, index, value) { if (!~index) classes.push(value); }), remove: update(function(classes, index) { if (~index) classes.splice(index, 1); }), toggle: update(function(classes, index, value) { if (~index) classes.splice(index, 1); else classes.push(value); }), contains: function(value) { return !!~self.className.split(/\s+/g).indexOf(value); }, item: function(i) { return self.className.split(/\s+/g)[i] || null; } }; } }); }
3、css鼠标指针事件
.disabled { pointer-events: none; }
禁止该元素的js事件和回调函数