我需要在两个不同的事件上以不同的速度更改元素的宽度。我可以以某种方式指定相同属性的两个过渡,还是必须更改方法?
假设我想通过悬停快速增加盒子的宽度。并能够通过按钮执行相同的操作,但速度较慢。这里的问题是当从框中删除该类时,3s转换也是如此。我希望3秒钟的过渡能够持续到再次按下按钮后框的缩小。
const box = document.getElementById("box");
function growQuickly(){
box.classList.toggle("grow");
}
.box{
height:100px;
width:100px;
background: red;
transition: .5s;
}
.box.grow{
width: 200px;
transition: 3s;
}
.box:hover{
width:200px;
}
<div class="box" id="box" ></div>
<button onclick="growQuickly()">GROW SLOWLY</button>
您可以将逻辑分为更多类,并使用js检查是否已包含某些内容。
.box {
height: 100px;
width: 100px;
background: red;
transition-duration: 0.5s;
}
.box:hover {
width: 200px;
}
.wide {
width: 200px;
}
.slow {
transition-duration: 3s;
}
const box = document.getElementById('box');
function growQuickly() {
const boxWidth = box.offsetWidth;
if (boxWidth === 200 && box.classList.contains('slow')) {
box.classList.toggle('wide');
setTimeout(() => box.classList.toggle('slow'), box.style.transitionDuration);
} else {
box.classList.toggle('wide');
box.classList.toggle('slow');
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句