18910140161

JavaScript-CAN't创建无限轮播-堆栈溢出

顺晟科技

2022-10-18 12:08:07

48

我所得到的只是计算一个元素的宽度,并找出它在屏幕上所占的百分比,但过渡并不平滑。CodeSandBox链接:https://codesandbox.io/s/fragrant-fire-ejxvd?file=/index.html.

const container = document.querySelector(".container");
const arrayOfElements = [];
let currentPercent = 0;
let percentOfElement = 0;

function createSlideElement() {
  const element = document.createElement("span");
  element.className = "slider-element";
  element.innerText = "|my ugly slide|";
  element.style.right = `${currentPercent}%`;
  container.append(element);
  arrayOfElements.push(element);
  const elementWidth = element.getBoundingClientRect().width;
  percentOfElement = (elementWidth / window.innerWidth) * 100;
}

function step() {
  currentPercent += 0.1;
  for (let el of arrayOfElements) {
    el.style.right = `${currentPercent}%`;
  }
  if (currentPercent >= percentOfElement) {
    currentPercent = 0;
  }
  window.requestAnimationFrame(step);
}

createSlideElement();
createSlideElement();
createSlideElement();

window.requestAnimationFrame(step); 

顺晟科技:

不使用window.innerWidth,而是使用container.getBoundingClientRect().width来计算percentOfElement

工作代码沙箱:-

Edit Infinite text slider

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航