用js监听css样式的变化
时间: 2024-04-14 15:27:28 浏览: 15
要使用JavaScript来监听CSS样式的变化,你可以使用MutationObserver API。下面是一个基本的示例:
```html
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
// 目标元素
const target = document.querySelector('.box');
// 创建MutationObserver实例
const observer = new MutationObserver((mutationsList, observer) => {
// 处理样式变化的回调函数
for(let mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
console.log('样式发生变化');
}
}
});
// 配置观察选项
const config = { attributes: true };
// 开始观察目标元素
observer.observe(target, config);
</script>
</body>
</html>
```
上述示例中,我们使用MutationObserver来监听目标元素的样式变化。当目标元素的style属性发生变化时,会触发回调函数,并打印出"样式发生变化"的消息。
你可以根据需要修改回调函数的逻辑,来执行你想要的操作。还可以根据需要配置其他观察选项,以满足具体的监测需求。