视差脚本在chrome和移动设备上延迟

Parallax script gets laggy in chrome and on mobile devices

本文关键字:延迟 移动 脚本 chrome 视差      更新时间:2023-09-26

我用这段代码为我正在创建的一个网站制作视差效果,在safari和firefox(mac)中效果很好。但在chrome(mac)中,它会出现延迟,我在iPad和iPhone 6上尝试时也是如此。

Javascript:

  var ypos,image;
  function parallax() {
    image = document.getElementById('bgImage');
    ypos = window.pageYOffset;
    image.style.top = ypos * .4+ 'px';
}
window.addEventListener('scroll', parallax),false;
html:

    <img class="img-responsive" id="bgImage" src="images/bgtopg.jpg">
</div>
     <div id="box1" class="content">
            <h1>Heading</h1>
            <p>Lorem ipsum dolor sit amet.....</p>      
        </div>

(img-responsive - from bootstrap)

css:

#bgImage {
    position: relative;
    z-index: -1
  }

你知道是什么导致了滞后效应吗?

怎么回事

javascript事件的'Laggy'行为是一个常见的问题。本质上,你遇到的是重载事件堆栈。它堆积得如此之高,以至于产生了波浪状的效果。

<标题> 你的选项

这个问题的解决方法有两个方面。您可以选择硬件加速或脱机的路径。卸载应该是你的第一个解决方案,当你确认你不是简单地重载你的脚本时,应该使用硬件加速。

揭穿那个混蛋!

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
document.addEventListener("DOMContentLoaded", function(event) { 
function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};
var myEfficientFn = debounce(function() {
	console.log("HEY STOP MOVING ME AROUND!");
}, 25);
window.addEventListener("mousemove", myEfficientFn),false;
});
Move your mouse around a whole lot and look at your console.

我们有加速的技术!

https://stackoverflow.com/a/15203880/1596825

你可以尝试用translateY做视差动画效果,而不是操纵图像的顶部样式。这是Paul Irish的一篇很棒的文章,它描述了为什么你应该做翻译而不是上/左/右/下。

所以不是:

image.style.top = ypos * .4+ 'px';

你可以这样做:

image.style.webkitTransform = 'translateY(' + ypos * .4 + 'px)';
image.style.transform = 'translateY(' + ypos * .4 + 'px)';
祝你好运,如果有帮助,请告诉我!