javascript - 如果在 setInterval 内不透明度 == 1,则将 1 添加到变量
问题描述
我有一个变量,每次元素opacity
为1
. 我需要继续检查不透明度,所以我将它包装在setInterval
.
我想知道是否有一种方法可以在每次不透明度更改为 1 时只向变量添加 1,而不是因为间隔而一遍又一遍地添加 1。这是我的代码
var number = 1;
var intervalsizer = setInterval(function() {
if ($(".cardButtons__discuss").css('opacity') == 1) {
number++;
console.log(number)
}
function fooo() {
if (number == 1) {
//do something
}
if (number == 2) {
}
if (number == 3) {
//do something
}
if (number == 4) {
//do something
}
}
}, 50);
提前致谢
解决方案
可以使用MutationObserver跟踪属性。此代码跟踪元素上的所有属性更改,并专门过滤掉style
和class
属性的更改。当属性更改时,它会查看不透明度值是否已更改。
此解决方案仅在元素本身的不透明度通过设置类或通过设置样式更改时才有效。
const mydiv = document.getElementById('mydiv')
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.attributeName !== 'style' && mutation.attributeName !== 'class') return;
const target = $(mutation.target);
const oldVal = target.data("oldOpacity");
const newVal = getComputedStyle(target[0]).opacity;
if(oldVal != newVal) {
console.log(`opacity changed. Old: ${oldVal}, New: ${newVal}`)
target.data("oldOpacity", newVal)
}
});
});
const config = {
attributes: true
};
observer.observe(mydiv, config);
//code to change the opacity and another style attribute.
let i = 0;
setInterval(() => {
switch (i % 4) {
case 0:
mydiv.style.backgroundColor = "red"
break
case 1:
mydiv.style.opacity = "0.5"
break
case 2:
mydiv.classList.add('blue')
break
case 3:
mydiv.style.opacity = ""
mydiv.classList.remove('blue')
mydiv.style.backgroundColor = "blue"
break;
}
i++;
}, 1000)
.blue {
background-color: blue !important;
opacity: 1 !important;
}
#mydiv {
background-color: red;
width: 100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
推荐阅读
- asp.net-mvc - 当关键参数是 EF DbContext 时,如何编写重用方法?
- database-connection - 无法使用 SQL Developer 登录?
- python - 将函数的输出重定向到python中的另一个文件夹
- javascript - getAttribute 不是函数
- javascript - 检索多个级别,API
- r - 在用户名中使用带有 @ 符号的包 RCurl ftpUpload
- java - 如何获得大量不同的 jar 文件?
- c# - 如何在删除视图中显示模型项的详细信息
- r - 如何在 R 中自定义数据结果的格式
- browser - 鉴于提供了 --user-agent,网站如何知道客户端不是浏览器?