Javascript 或 CSS 中的缓慢滚动背景?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8646912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Slow scrolling background in Javascript or CSS?
提问by Armin
I'm trying to figure out how to make a background image scroll slower than the page contents. I haven't got a clue how it's done. The perfect example of what I'm trying to do is here
我想弄清楚如何使背景图像滚动得比页面内容慢。我不知道它是如何完成的。我正在尝试做的事情的完美例子是here
Is this done in CSS or jQuery/Javascript?
这是用 CSS 还是 jQuery/Javascript 完成的?
回答by Armin
This is made by javascript (jQuery):
这是由 javascript (jQuery) 制作的:
(function () {
var a = document.body,
e = document.documentElement;
$(window).unbind("scroll").scroll(function () {
a.style.backgroundPosition = "0px " + -(Math.max(e.scrollTop, a.scrollTop) / 8) + "px";
});
})();
回答by lorenzo-s
The effect on the link you posted is done in Javascript using jQuery.
对您发布的链接的影响是使用 jQuery 在 Javascript 中完成的。
If you examine the code of a script of the site here, you can find:
如果您在此处检查站点脚本的代码,您会发现:
.style.backgroundPosition="0px "+-(Math.max(e.scrollTop,a.scrollTop)/8)+"px"
Practically, the background-position
CSS property is modified on page scrolling calculating Y-axis depending on page scroll position. If you have some knowledge of Javascript, jQuery or Mootools, you can reproduce the effect very easily.
实际上,background-position
根据页面滚动位置在页面滚动计算 Y 轴上修改 CSS 属性。如果您对 Javascript、jQuery 或 Mootools 有一定的了解,则可以非常轻松地重现该效果。
I think it's impossible to do it using only CSS.
我认为仅使用 CSS 是不可能的。
回答by Valentin Seehausen
This one works for high bg images.
这个适用于高 bg 图像。
(function () {
var body = document.body,
e = document.documentElement,
scrollPercent;
$(window).unbind("scroll").scroll(function () {
scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
body.style.backgroundPosition = "0px " + scrollPercent + "%";
});
})();