仅使用CSS转换来增加值

时间:2018-03-07 08:55:03

标签: css css3 css-transitions transition

在我的代码中,我只想在宽度变宽时才使用过渡。 当宽度减小时,我不想要任何动画。 我只能用CSS吗?添加/删除类不适合我。



function changeCss() {
  document.getElementById('squareId').style.width = "300px";
}

function reset() {
  document.getElementById('squareId').style.width = "100px";
}

.square {
  background-color: red;
  width: 100px;
  height: 100px;
  transition: width 1s linear;
}

<div id="squareId" class="square"></div>

<button onclick="changeCss()">increase</button>
<button onclick="reset()">decrease</button>
&#13;
&#13;
&#13;

JSFiddle

1 个答案:

答案 0 :(得分:2)

在JS代码中同时调整转换:

window.changeCss = function() {
  document.getElementById('squareId').style.transition = "width 1s linear";
  document.getElementById('squareId').style.width = "300px";
}
window.reset = function() {
  document.getElementById('squareId').style.transition = "none";
  document.getElementById('squareId').style.width = "100px";
}
.square {
  background-color: red;
  width: 100px;
  height: 100px;
}
<div id="squareId" class="square">

</div>
<button onclick="changeCss()">increase</button>
<button onclick="reset()">decrease</button>