有人可以帮助我,如何最好地优化javacript代码的下方部分?
我想让浏览器最轻松,但我不知道 - 我对javascript知之甚少。
if ($(window).width() > 1200) {
(function() {
var parallaxTop = document.querySelectorAll(".parallax-top");
if ($(".parallax-center").length) {
var parallaxCenter = document.querySelectorAll(".parallax-center");
var centerPosition = $(".parallax-center").position().top;
}
if ($(".parallax-bottom").length) {
var parallaxBottom = document.querySelectorAll(".parallax-bottom");
var bottomPosition = $(".parallax-bottom").position().top;
}
var speed = 0.4;
window.onscroll = function() {
[].slice.call(parallaxTop).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "-" + (windowYOffset * speed) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
if ($(".parallax-center").length)
[].slice.call(parallaxCenter).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "" + ((windowYOffset - centerPosition) * speed + 1700) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
if ($(".parallax-bottom").length)
[].slice.call(parallaxBottom).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "" + ((windowYOffset - bottomPosition) * speed + 1400) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
};
})();
}