繁体   English   中英

如果setInterval中的不透明度== 1,则将1加到变量中

[英]Add 1 to variable if opacity is == 1 within a setInterval

我有一个变量,每次元素opacity1时,都需要加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来跟踪属性。 此代码跟踪元素上所有属性的更改,并专门过滤掉styleclass属性的更改。 当属性更改时,将查看不透明度值是否已更改。

仅当通过设置类或设置样式更改元素本身的不透明度时,此解决方案才有效。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM