javascript - 无法制作无限轮播
问题描述
我得到的只是计算一个元素的宽度并找出它在屏幕上所占的百分比,但过渡并不平滑。代码沙盒链接: 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
类似的:-
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);
工作代码沙箱:-
推荐阅读
- asp.net-core - 更新 CosmosDB 中的类型化对象
- xamarin - 在 Xamarin.Forms 中设计和打印 PDF
- angular - 离子使用角度 HTTP POST 不会调用 Android 模拟器上的 API
- c# - WebBrowser 控件抛出大量 JavaScript 错误
- jquery - 无法遍历从 AJAX 请求返回的 JSON
- python - Python 检查几个 if 条件(用数字查找和替换单词)
- python - 在 python 中解析此文本的最佳/更清洁的方法是什么?
- sql-server - Create an Alert in SQL if a field in a table decreases (Seq number Control Table)
- kotlin - 为什么在获取 JSON 时会出现 NullPointerException?
- linux - IIS 中的子站点映射