首页 > 解决方案 > 每次文本更改时如何设置过渡

问题描述

每次单击按钮时如何使用innerHTML方法添加文本时如何设置文本的过渡。

我所做的是在css上设置一个过渡,但它只影响空间为空并且我第一次单击一个按钮并出现文本时,但它不影响当我单击其他按钮并且文本发生变化时,我有什么还尝试在 javascript 文件的 getElementByID 中设置 .style.transition 但它不起作用。

var name;

function something(json) {
  name = json.data.name;
  document.getElementById("text1").innerHTML = "Haz añadido " + name +
    " ,ahora elige tu cantidad";
  document.getElementById("text1").style.color = "white";
  document.getElementById("text1").style.trasition = "1s";
}
h5#text1 {
  color: "white";
  text-align: center;
  width: 100%;
  position: relative;
  margin: 3% 0 5% -20%;
  transition: 1s;
}
<form get="/page2/bisagras/cambio.html" method="post">

  <button type="button" class="btn btn-light bn" id="1"> 
                 <span class="dif">3/8"</span> Q2.15</button>
  <button type="button" class="btn btn-light bn" id="2"> 
                 <span class="dif">1/2"</span> Q2.90</button>
  <button type="button" class="btn btn-light bn" id="3"> 
                 <span class="dif">5/8"</span> Q3.75</button>

</form>


<div class="cant">
  <h5 id="text1"></h5> //THIS IS THE WHERE APPEARS THE TEXT
</div>

我期望的是每次在 HTML 中单击按钮时,文本会像淡入一样缓慢出现

标签: javascripthtmlcss

解决方案


您可以从这里运行示例jsfiddle

function show() {
  var textElement = document.getElementById("text");
  if (textElement.className) {
    textElement.className = '';
  }
  textElement.className = 'fadeOut';
  textElement.innerHTML = Math.random().toString(36).substring(7);
  textElement.focus(); // use focus trick without setTimeOut
  textElement.className = 'fadeIn';
}
.fadeOut {
  opacity: 0;
}

.fadeIn {
  opacity: 1;
  transition: all 1s;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -ms-transition: all 1s;
  -o-transition: all 1s;
}
<p id='text'></p>
<button onclick='show()'>Show</button>


推荐阅读