为什么在删除班级时应用过渡?

时间:2018-08-28 10:37:46

标签: javascript css

Here is an example of my problem

我有一个div和一个button。每次单击按钮时,div会将background-color更改为随机颜色。

button.addEventListener('click', function(e){
    e.preventDefault();
    setRandomColor();
});

默认情况下,div具有一个名为transition-on的类,该类将过渡应用于background-color

<div class="block transition-on"></div>
<button>Change</button>

CSS:

.transition-on {
  transition: background-color 0.5s
}

如果我在应用随机background-color之前删除了该类,然后在之后重新应用该类,则过渡仍然适用。

我的目的是在应用随机颜色时临时删除过渡。

button.addEventListener('click', function(e){
    e.preventDefault();
    block.classList.remove('transition-on');
    setRandomColor();
    block.classList.add('transition-on');
});

有人知道为什么会这样吗?

编辑:

请参考@ths的答案-使用setTimeout确实会产生我需要的结果,但是现在我想知道为什么有必要使用超时。

是否真的需要超时才能暂时禁用CSS转换?

  • 删除过渡课程
  • 将颜色应用于块
  • 重新添加过渡类

这应该从逻辑上改变颜色而无需过渡

2 个答案:

答案 0 :(得分:0)

从id =“ remove_trans”元素中删除“ transition-on”类:

  function changecolor()
    {
//add this code 
       var element = document.getElementById("remove_trans");

       element.classList.remove("transition-on");
        setRandomColor();
        element.classList.add('transition-on');
     }

    changecolor();

html

div id="remove_trans" class="block transition-on"></div>
<button onClick="changecolor()">Change</button>

在html标签中添加id属性

答案 1 :(得分:0)

据我所知,您想使用background-color动态更改JavaScript而不看到任何过渡。为此,您需要添加将transition-on类添加到div方法中的setTimeout元素并通过将transition-duration传递给第二个参数的表达式(在您的情况下transition-duration等于0.5s。

下面是一个可运行的代码段,用于说明:

var block = document.querySelector('.block');
var button = document.querySelector('button');

function setRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  block.style.backgroundColor = color;
}

button.addEventListener('click', function(e){
  e.preventDefault();
  block.classList.remove('transition-on');
  setRandomColor();
  // the next line executes after 500 ms, thus the div element gets the transition-on class after 500 ms and no transition will happen.
  setTimeout(function() {
    block.classList.add('transition-on');
  }, 500); // 500 ms = 0.5 s => the transition-duration of the transition-on class
});
setRandomColor();
.block {
  width: 40px;
  height: 40px;
}
.transition-on {
  transition: background-color 0.5s
}
<div class="block transition-on"></div>
<button>Change</button>