最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Slow scrolling background in Javascript or CSS? - Stack Overflow

programmeradmin5浏览0评论

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

Is this done in CSS or jQuery/Javascript?

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

Is this done in CSS or jQuery/Javascript?

Share Improve this question asked Dec 27, 2011 at 16:33 user1101990user1101990 3
  • 2 This used to be called parallax scrolling back when I was a kid and wanted to make games. There seem to be some resources that use the same term out there (e.g. when Googling jquery parallax scrolling) – Pekka Commented Dec 27, 2011 at 16:35
  • 5 Javascript. Significantly easier with jQuery, but it also requires special HTML/CSS markers. Cool, simple example at inner.geek.nz/javascript/parallax . You could also just google parallax scrolling. – Edwin Commented Dec 27, 2011 at 16:38
  • @Edwin : Thank you for pointing out the proper name. – user1101990 Commented Dec 27, 2011 at 16:49
Add a comment  | 

3 Answers 3

Reset to default 15

This is made by 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";
    });
})();

The effect on the link you posted is done in Javascript using jQuery.

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.

I think it's impossible to do it using only CSS.

This one works for high bg images.

(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 + "%";
        });
})();
发布评论

评论列表(0)

  1. 暂无评论