在 Chrome 浏览器中的窗口上闪烁移动 html 元素

问题描述 投票:0回答:1

我在水平移动时遇到垂直线闪烁的问题。在非恒定间隔中,这条线只是消失一段时间。

我创建了一个小游乐场来重现这个问题。

let i = 0;
(function tick() {
  requestAnimationFrame(() => {
    const playhead = document.querySelectorAll("div.playhead")[0];
    playhead.style.left = i + "px";
    if (i === 500) return;
    i++;
    tick();
  });
})();
.container {
  position: relative;
  border: 1px solid gray;
  width: 500px;
  height: 100px;
}

.playhead {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 1px;
  background-color: red;
  z-index: 3;
  user-select: none;
}
<div class="container">
  <div class="playhead" />
</div>

该问题出现在 Windows 上的 Chrome 中,在 macOS 上一切正常。

javascript windows google-chrome animation flicker
1个回答
0
投票

一般来说,你应该尝试使用

transform
属性,而不是更改元素的
position

let i = 0;
(function tick() {
  requestAnimationFrame(() => {
    const playhead = document.querySelectorAll("div.playhead")[0];
    playhead.style.transform = `translateX(${i}px)`
    if (i === 500) return;
    i++;
    tick();
  });
})();
.container {
  position: relative;
  border: 1px solid gray;
  width: 500px;
  height: 100px;
}

.playhead {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 1px;
  background-color: red;
  z-index: 3;
  user-select: none;
}
<div class="container">
  <div class="playhead" />
</div>

第二种解决方案是在

will-change
上使用
playhead
属性(请参阅 css 部分),但我强烈建议在此类情况下使用 Transform。

let i = 0;
(function tick() {
  requestAnimationFrame(() => {
    const playhead = document.querySelectorAll("div.playhead")[0];
    playhead.style.left = i + "px";
    if (i === 500) return;
    i++;
    tick();
  });
})();
.container {
  position: relative;
  border: 1px solid gray;
  width: 500px;
  height: 100px;
}

.playhead {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 1px;
  background-color: red;
  z-index: 3;
  user-select: none;
  will-change: left;  /* I ADDED THIS LINE ONLY */
}
<div class="container">
  <div class="playhead" />
</div>

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.