After testing your JavaScript example on a random list in iOS Safari and macOS Chrome, I noticed that while it does work, the performance is not optimal. The animations appear chunky and janky because of the constant recalculation of layout and flow by the browser. Each time you update the line-height of one list item, all subsequent items are affected, leading to inefficient processing. To improve this, consider using paint or composite-related properties instead of layout/flow adjustments.
For better performance, check out this resource: https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/
If I were tackling this issue, I would suggest utilizing the transform property with unique translateY values for each list item after initially setting them up with a consistent line-height. This approach also prevents the entire list height from changing with every update, thus avoiding continuous recalculation of scrollHeight during scrolling.
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>