首页 > 解决方案 > 如果在 setInterval 内不透明度 == 1,则将 1 添加到变量

问题描述

我有一个变量,每次元素opacity1. 我需要继续检查不透明度,所以我将它包装在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);

提前致谢

标签: javascriptjquerysetintervalvar

解决方案


可以使用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>


推荐阅读