【问题标题】:Can't make an infinite carousel无法制作无限轮播
【发布时间】:2021-09-15 13:11:25
【问题描述】:

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

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    使用container.getBoundingClientRect().width 代替window.innerWidth 来计算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);
    

    工作代码沙箱:-

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 2023-03-12
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2022-01-23
      • 1970-01-01
      • 2011-10-29
      相关资源
      最近更新 更多