#box {
width: 100px;
height: 100px;
background-color: red;
}
<button id="btn">click</button>
<div id="box"></div>
<script>
const box = document.getElementById('box');
const btn = document.getElementById('btn');
document.getElementById('btn').addEventListener('click', function() {
box.style.transform = 'translateX(1000px)';
box.style.transition = 'transform 1s ease-in-out';
getComputedStyle(box).transform;
box.style.transform = 'translateX(500px)';
});
// method 1
document.getElementById('btn').click();
// method 2
setTimeout(() => {
btn.click();
}, 1000)
</script>
context:
Google: 版本 92.0.4515.107(正式版本) (x86_64)
Firefox: 版本: 90.0.2 (64 位)
In above code, method 1 and method 2 will lead different animation in both browers。 why? I'm not talking about 1s delays
example:
https://codesandbox.io/s/compassionate-tharp-ommki?file=/index.html and then change code, take a look
Results:
Your code with method #1 will work if you wrap all the code into:
About event.
It works because code will work after css was parsed and applied to element.
Current code fires before this. It causes to "jumping" of the element.