我制作了一个JS效果来增加滚动时我网站的每行的行高。它可以在Macbook和Android智能手机上正常运行,但不能在iPhone上运行。有人有解决方案吗?
function throttled(delay, fn) {
let lastCall = 0;
return function(...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
const testElement = document.querySelectorAll("li");
console.log(testElement.offsetTop);
window.addEventListener("scroll", throttled(10, (e) => {
for(let i = testElement.length-1;i>=0;i--){
let posTopElement = (testElement[i].offsetTop)-600;
if (document.documentElement.scrollTop > posTopElement) {
window.requestAnimationFrame(function() {
let minLineHeight = 4;
let lineHeight = (window.scrollY - posTopElement) * 0.1;
if (lineHeight < minLineHeight) lineHeight = minLineHeight;
else if (lineHeight > 36) lineHeight = 36;
testElement[i].style.lineHeight = lineHeight + "px";
});
}
}
}));
答案 0 :(得分:0)
因此,当我以您的示例js并将其放到某些随机列表元素的顶部时,它对我来说在iOS Safari中的工作原理与在macOS Chrome中一样。但是两者都非常笨拙/笨拙,因为您要求浏览器以几乎递归的方式重新计算布局/流。更新单个li的行高时,将重新排列所有后续li元素的布局。这确实是昂贵/低效的。与其更新与布局/流相关的属性,不如找到一种方法来使用涂料或更好的与合成相关的属性来创建所需的效果。
https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/
如果是我,在最初以一致的行高对其进行布局之后,我将尝试找到一种方法,对每个li使用具有唯一transform
值的translateY
属性。这样做的好处还在于,每次更新时都不会改变整个列表的高度,因此,不会在滚动过程中一遍又一遍地重新计算窗口的scrollHeight。
function throttled(delay, fn) {
let lastCall = 0;
return function(...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
const testElement = document.querySelectorAll("li");
console.log(testElement.offsetTop);
window.addEventListener("scroll", throttled(10, (e) => {
for(let i = testElement.length-1;i>=0;i--){
let posTopElement = (testElement[i].offsetTop)-600;
if (document.documentElement.scrollTop > posTopElement) {
window.requestAnimationFrame(function() {
let minLineHeight = 4;
let lineHeight = (window.scrollY - posTopElement) * 0.1;
if (lineHeight < minLineHeight) lineHeight = minLineHeight;
else if (lineHeight > 36) lineHeight = 36;
testElement[i].style.lineHeight = lineHeight + "px";
});
}
}
}));
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, width=device-width, maximum-scale=1, user-scalable=no, shrink-to-fit=no, viewport-fit=cover">
<style>
ul {
min-height: 200vh;
overflow: hidden;
}
</style>
</head>
<body>
<ul>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
</ul>
</body>
</html>