Stops the floating js on the phone.
-
I need to make a smooth sweep.
scroll-behavior: smooth;
andwindow.scrollTo({ top: to, behavior: "smooth" });
- It doesn't work because it doesn't work in Safari. I've done it on this pattern:- I get the position of the component (where it is relatively complete at height)
- Got it.
window.pageYOffset
- current status of the port. - I'm checking out the distance.
- Through
window.scrollBy
I'll cover it down.дистанция/скорость
- Repeat the above actions if the distance to the target is greater than the point of the wire
setTimeout
♪
It's all right on the belt, it's all right, it's gonna be slow down to the element. On the phone. Why is that and what can be done?
The use of libraries is not desirable.
Here's the code:
class jscroll {
static to(item) { const stepCoefficient = 100; const timer = 1; let to = document.querySelector(item).getBoundingClientRect().top; let distance = to - window.pageYOffset + stepCoefficient; let step = 10; let oldStep; function scroll() { oldStep = step; step = distance / stepCoefficient; window.scrollBy(0, step); distance = to - window.pageYOffset + stepCoefficient; if (step > 1 && step != oldStep) setTimeout(scroll, timer); else window.scrollTo(0, to); } scroll(); } } export { jscroll }
-
Checked on the mobile device.
I think that the cause of unmanned work can be too frequent a challenge to the function (a total of 1 millisecond delay before new performance). It should be called about 17 times less (for an ordinary screen with 60 Hz frequency). With help https://developer.mozilla.org/ru/docs/Web/API/window/requestAnimationFrame You can make challenges that "most common to the screen renewal frequency" and not overload the device.
In my example, the numbering facilitates the verification of melting. Modified
offset
Responsibilities, butspeed
- for the speed of slinging.function scrollTo(item) { let offset = 0; let speed = 20;
let to = document.querySelector(item).getBoundingClientRect().top; let dy = to - window.pageYOffset + offset; let moreZero = (dy >= 0)? 1 : -1; let dist = dy * moreZero; let step = speed * moreZero; window.requestAnimationFrame((scroll = function() { if ((dist -= speed) > 0) { window.scrollBy(0, step); window.requestAnimationFrame(scroll); } }));
}
document.getElementsByTagName("button")[0].onclick = () => {
scrollTo("#l");
}// ниже - создание элементов для проверки
function createDivs() {
for (let i = 0; i < 200; i++) {
let e = document.createElement("div");
e.innerHTML = i;
document.body.appendChild(e);
}
let e = document.createElement("div");
e.id = "l";
document.body.appendChild(e);
}
createDivs();<button>Scroll</button>