首页 > 解决方案 > 无法制作无限轮播

问题描述

我得到的只是计算一个元素的宽度并找出它在屏幕上所占的百分比,但过渡并不平滑。代码沙盒链接: 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); 

标签: javascripthtmlcss

解决方案


而不是window.innerWidth,container.getBoundingClientRect().width用来计算percentOfElement类似的:-

import "./styles.css";

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;
  const parentWidth = container.getBoundingClientRect().width;
  percentOfElement = (elementWidth / parentWidth) * 100;
}

function step() {
  currentPercent += 1;

  for (let el of arrayOfElements) {
    el.style.right = `${currentPercent}%`;
  }

  if (currentPercent >= percentOfElement) {
    currentPercent = 0;
  }

  window.requestAnimationFrame(step);
}

createSlideElement();
createSlideElement();
createSlideElement();
window.requestAnimationFrame(step);

工作代码沙箱:-

编辑无限文本滑块


推荐阅读