【问题标题】:Parallax script gets laggy in chrome and on mobile devices视差脚本在 chrome 和移动设备上变得迟钝
【发布时间】:2015-08-15 03:10:55
【问题描述】:

我将此代码用于我正在创建的网站的视差效果,在 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 - 来自引导程序)

css:

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

任何想法是什么导致了滞后效应?

【问题讨论】:

  • 尝试使用 CSS 转换来设置元素的位置,
  • 阅读完我的答案后,您应该观看此内容以轻松了解 javascript 事件堆栈的工作原理。优酷:youtube.com/watch?v=8aGhZQkoFbQ

标签: javascript html css parallax


【解决方案1】:

发生了什么

javascript 事件的“滞后”行为是一个常见问题。本质上,您遇到的是超载事件堆栈。它堆积得如此之高,以至于产生了波涛汹涌的效果。

您的选择

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

去抖那个混蛋!

// 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

【讨论】:

  • 不确定我应该如何使用去抖动!
  • 你应该阅读它。如果不正确控制事件侦听器,就无法制作出好的 JavaScript。
  • 我会的!感谢您的信息:)
  • 谢谢你,派上用场了。
【解决方案2】:

您可以尝试使用 translateY 来制作视差动画效果,而不是操纵图像的顶部样式。 This is an excellent post Paul Irish 描述了为什么你应该进行翻译而不是 top/left/right/bottom。

所以而不是:

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

你可以这样做:

image.style.webkitTransform = 'translateY(' + ypos * .4 + 'px)';
image.style.transform = 'translateY(' + ypos * .4 + 'px)';

祝你好运,如果有帮助请告诉我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多