JavaScript和css交互
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事件和回调函数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结