在Javascript中设置样式更改事件监听器 [英] Set style change event listener in Javascript

查看:148
本文介绍了在Javascript中设置样式更改事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的div看起来像这样:

My div looks something like this:

<div tabindex="0" role="button" id="profile-pic" style="background-image: "Some url";"></div>

背景图片将根据某些条件进行更新。我想将侦听器设置为样式属性,并侦听背景图像更改。

The background image will be updated based on some criteria. I want to set listener to the style property and listen to background image change. Is it possible?

推荐答案

您可以使用 MutationObserver

然后代码示例:

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
    console.log('style changed!');
   });    
 });

 var target = document.getElementById('myId');
  observer.observe(target, { attributes : true, attributeFilter : ['style'] });

注意:这仅适用于内联样式(样式的任何更改),不适用于样式更改为类更改或@media更改的结果
这是一个答案 https://stackoverflow.com/a/20683311/3344953

Note: this only works with inline styles(any changing of styles), not when the style changes as a consequence of class change or @media change This is a answer https://stackoverflow.com/a/20683311/3344953

这篇关于在Javascript中设置样式更改事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆