给定
var box = document.querySelector('.box');
document.addEventListener("click", (event) => {
if (!event.target.closest("button")) return;
if(event.target.id === "button") {
box.classList.add('move');
}
});
.box {
width: 100px;
height: 100px;
background-color: #000;
transition: transform 1s;
}
.move {
transform: translateX(20px);
}
<div class="box"></div>
<button id="button">button</button>
用 JS Fiddle here .
我希望盒子的 x 位置增加
20px
在每个按钮点击。我不确定如何进行。我最初尝试使用
@KeyForms
但这需要 from
和 to
前缀,我不能(我认为)在其上添加变量值。这里出现了同样的问题,似乎我不能在 css 代码中有一个可以递增的变量。我是否使用了正确的功能(transition
)?我也试过
if(event.target.id === "button") {
if(!box.classList.contains('open')){
box.classList.add('open');
}else {
box.classList.remove('open');
}
}
但这似乎重复地来回移动盒子。有没有人有任何提示或想法? (我正在添加 Javascript 标记,因为我怀疑这个问题可能会直接在 JS 中解决)。
最佳答案
您可以存储 x
变量中的位置,每次单击增加 20 并将其应用于 transform
样式属性:
var x = 0, box = document.querySelector('.box');
button.addEventListener('click', function() {
x += 20, box.style.transform = `translateX(${x}px)`;
})
.box {
width: 100px;
height: 100px;
background-color: #000;
transition: 1s;
}
<div class="box"></div>
<button id="button">button</button>
关于javascript - 每次单击按钮时 CSS 递增过渡动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68434702/