简体   繁体   English

使用 JavaScript 同时转换多个元素

[英]Transition on multiple elements at the same time using JavaScript

Cheers.干杯。 I'm having an issue debugging certain behavior that occurs mostly in the Chrome browser: Here is the simplified example: https://jsfiddle.net/pd3xb2uo/我在调试主要发生在 Chrome 浏览器中的某些行为时遇到问题:这是简化的示例: https://jsfiddle.net/pd3xb2uo/

The objective is to transition multiple elements via JS code at the same time.目标是同时通过 JS 代码转换多个元素。 In the example when you click on the button, items are moved to the left using translate3d added via JS.在示例中,当您单击按钮时,项目将使用通过 JS 添加的translate3d移动到左侧。 It works fine, but there are some caveats:它工作正常,但有一些警告:

  1. There is a small gap appearing between the items most of the time大多数时候项目之间会出现一个小差距
  2. Sometimes when you click faster on the button there is a large gap appearing between the items.有时,当您更快地单击按钮时,项目之间会出现很大的差距。

Here are the screenshots of both cases:以下是两种情况的截图:

小间隙

差距大

Any help or ideas on why it is happening would be highly appreciated:) It looks like there is a few milliseconds delay before the style attribute is updated on certain elements, but I have no idea why:/任何关于为什么会发生这种情况的帮助或想法将不胜感激:)看起来在某些元素上更新样式属性之前有几毫秒的延迟,但我不知道为什么:/

The problem occurs because you are transitioning 100 elements at the same time and because of half-pixel transitions.出现此问题是因为您同时转换 100 个元素并且半像素转换。

If you know how wide and how many elements you have, then you can do it like so:如果你知道你有多少宽度和多少元素,那么你可以这样做:

 const container = document.querySelector('.container-inner'); for (let i = 1; i < 100; i++) { const div = document.createElement('div'); div.classList.add('element'); div.textContent = `Element ${i}`; container.appendChild(div); } let transition = 0; document.querySelector('button').addEventListener('click', () => { transition -= 100; container.style.transform = `translateX(${transition}px)`; });
 .container{ width: 100%; overflow: hidden; }.container-inner{ display: flex; flex-direction: row; transition: transform.3s; }.element { width: 100px; box-sizing: border-box; display: flex; justify-content: center; align-items: center; padding: 2rem; text-align: center; transition: transform.3s; background-color: #A67583; }
 <button>Move</button> <div class="container"> <div class="container-inner"></div> </div>

Now only one element gets transitioned and it is working smoothly.现在只有一个元素被转换并且运行顺利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM