2017-01-08 1 views
0

Я пытаюсь сделать эффект параллакса, который включает только фоны и изображения заголовка/нижнего колонтитула, оставляя только основную разметку контента (обычный цикл wordpress).Применение эффекта прокрутки параллакса к нескольким фонам, каждая прокрутка в другом темпе

Фоны все в DIV #page который занимает весь документ, на верхний баннер, который находится в отдельном DIV в верхней части, .site-brandingimg за исключением, и заполнения фона, который находится в body.

#page { 
    background:url("http://i.imgur.com/jK3tbU8.png") no-repeat scroll bottom center, url("http://i.imgur.com/TSrLfq1.png") repeat-x scroll top center, url("http://i.imgur.com/Md0r0mw.png")repeat-x scroll bottom center; 
    padding:0; 
    margin:0; 
    transition: 0s ease-in-out; 
    transition-property: background-position; 
} 

body { 
    background:url("http://i.imgur.com/910XVzz.jpg") repeat scroll top; 
    padding:0; 
    margin:0; 
    transition: 0s ease-in-out; 
    transition-property: background-position; 
} 

.site-branding { 
    margin-left:auto; 
    margin-right:auto; 
    min-width: 0; 
    overflow: hidden; 
    display: block; 
} 
.site-branding img { 
    max-width:100%; 
    margin-left:0; 
} 

Верхний баннер прокручивает на определенной скорости, верхний фон прокручивается вверх на несколько более медленными темпами, заполняющие свитки обычно в середине страницы ...

До сих пор так хорошо (пожалуйста, обратитесь к JSFiddle, приведенному ниже, чтобы следовать за всем этим немного удобнее).

Затем я хочу сделать два нижних фона, jK3tbU8.png и Md0r0mw.png, для прокрутки вверх на их собственной скорости (например, медленнее, чем свиток), в конце концов остановки в нижней части страницы (jK3tbU8.png является «мандала «Нижний колонтитул, который находится на верхней части jK3tbU8.png, нижний фон исчезает).

С помощью приведенного ниже сценария я могу заставить их подняться со своей скоростью: но Я не могу заставить их остановиться точно внизу.

Я думаю, что это может произойти главным образом потому, что scrollTop() и offset() все основаны на верхней ...?

Вы могли бы подумать, что это всего лишь вопрос вычитания значений, но я нахожу, что высота области просмотра, конечно, имеет значение. Если видовой экран меняется, изображения заканчиваются в более высоком или нижнем положении, хотя и с очень небольшими различиями.

Наверное, мне нужно учитывать фактор просмотра в расчете? но я не знаю, как!

Вот весь мой код, я много комментариев в нем, надеюсь, это будет не так уж трудно понять:

jQuery(function ($) { 
    "use strict"; 

    $(document).ready(function(){ 
    var $win = $(window); 

    $('div#page').each(function(){ 

     //set an arbitrary "speed" 
     var scroll_speed1 = 8; 

     var viewportHeight = $(window).height(); 

     //set heights of backgrounds (any easy way to get this dynamically?) 
     var topFade = 600; 
     var bottomFade = 870; 
     var mandalaBottom = 457; 

     var $this = $(this); 

     //set background-attachment here, so that in style.css top-fade can be "scroll" 
     //needed in case the script breaks 
     $this.css("background-attachment", "scroll, fixed, scroll"); 

     //set all the initial positions 
     //the idea is that if the images are down below (= higher number) 
     //they will scroll up faster, at a matching speed (= number dimishing faster) 
     var bgP1 = (($this.outerHeight()*2) + mandalaBottom); //mandala-bottom 
     var bgP2 = $this.offset().top; //top-fade 
     var bgP3 = ($this.outerHeight()+(bottomFade)); //bottom-fade 
     var initialValue = "center " + bgP1 + "px," + "center " + bgP2 + "px," + "center " + bgP3 + "px"; 

     //put the images in the css 
     $this.css("background-position", initialValue); 

     //bind to the scroll event 
     $(window).scroll(function() { 

      //percent between viewport and height of page 
      var viewportDiff = percentChange($this.outerHeight(), viewportHeight); 
      console.log("the percent between viewport and height of page is: " + viewportDiff+ "%"); 

      //percent between position of pic and height of page 
      var perDiff = percentChange(bgP1, $this.outerHeight()); 
      console.log("the percent between position of pic and height of page is: " + perDiff); 

     /* 1) $win.scrollTop() = position of the scroll (increasing number) 
      2) perDiff = the proportion between the page and the position of the pic (%) 
      3) viewportDiff= the proportion between the page and the viewport (%) 
      4) $this.outerHeight() = height of the page 
      => scroll + the x% of scroll (given by the difference with the position of the pic) - the x% of page (given by the difference between viewport and page) + the height of the image */    
      var numberToSubstract = ($win.scrollTop() + percentOf($win.scrollTop(), perDiff) - percentOf(viewportDiff, $this.outerHeight()) + (mandalaBottom/2)); 
      console.log("the initial position of the pic was: " + bgP1); 
      console.log("we have substracted this much: " + numberToSubstract); 
      var bgNP1 = bgP1 - numberToSubstract - (mandalaBottom); 
      console.log("the pic now is here: " + bgNP1); 
      console.log("the height of the page is: " + $this.outerHeight());    


      //this calculates where to put the top-fade as the page is scrolled 
      var bgNP2 = -(($win.scrollTop() - $this.offset().top)/ scroll_speed1); 

      //this calculates where to put the bottom-fade as the page is scrolled 
      var perDiff3 = percentDiff(bgP3, $this.outerHeight()); 
      var numberToSubstract3 = ($win.scrollTop() + percentOf($win.scrollTop(), perDiff3))/scroll_speed1; 
      var bgNP3 = bgP3 - numberToSubstract3 - bottomFade; 
      //put the new values in the css 
      var newValue = "center " + bgNP1 + "px," + "center " + bgNP2 + "px," + "center " + bgNP3 + "px"; 
      $this.css("background-position", newValue); 

      }); //scroll 
     }); //page 

      //this takes care of mandala-top 
      $('div.site-branding').each(function(){ 

       //set an arbitrary speed 
       var scroll_speed = 1.5; 

        //bind to the scroll event (again?) 
        $(window).scroll(function() {    

         //this calculates where to put the top-fade as the page is scrolled 
         var bgNP2 = -(($win.scrollTop() /*- $this.offset().top --not needed since it is 0*/)/scroll_speed); 

         //put the new values in the css 
         var newValue2 = bgNP2 + "px"; 
         $('#mandalaTop').css("position", "relative"); 
         $('#mandalaTop').css("top", newValue2); 
         $('#mandalaTop').height(448 /*height of top img*/); 

        }); //scroll 

     }); //div.site-branding 

    });//document ready 

    if(navigator.userAgent.match(/Trident\/7\./)) { 
     $('body').on("mousewheel", function() { 
      event.preventDefault(); 
      var wd = event.wheelDelta; 
      var csp = window.pageYOffset; 
      window.scrollTo(0, csp - wd); 
     }); 
    } 

    //following this calculation: 
    //http://www.calculatorsoup.com/calculators/algebra/percent-difference-calculator.php 
    function percentDiff(val1, val2) { 
     var difference = ((val1 - val2)/((val1+val2)/2)) * 100; 
     return difference; 
    } 

    function percentOf(percent, value) {   
     var n = percent/100; 
     return n * value; 
    } 

    function percentChange(bigVal, smallVal) { 
     var change = ((smallVal-bigVal)/bigVal) * 100; 
     return 100 + change; 
    } 

}); 

Чтобы понять выше немного лучше, и увидеть простой HTML которая содержит все это, вот JSFiddle.

Он работает так, как должен, а это значит, что все в порядке сверху, но испорчено внизу.

ответ

0

Очень простое решение проблемы заключается в изменении:

//put the new values in the css 
var newValue = "center " + bgNP1 + "px," + "center " + bgNP2 + "px," + "center " + bgNP3 + "px"; 

To:

//put the new values in the css 
var newValue = "center bottom," + "center " + bgNP2 + "px," + "center " + bgNP3 + "px"; 

В принципе, не назначая динамический свитка смещение нижнего декоративного элемента, так как вы хотите, чтобы придерживаться нижней части.

Если вы все еще хотите анимировать, но нижний элемент, но придерживайтесь его до дна, это может сделать простой условный. В этом случае 457 - высота изображения.Таким образом, если смещение когда-либо становится меньше, чем высота страницы - высота изображения, наклеить изображение вниз, чтобы избежать разрыва:

if(bgNP1 < $this.outerHeight() - 457) 
{ 
    bgNP1 = $this.outerHeight() - 457; 
} 

//put the new values in the css 
var newValue = "center " + bgNP1 + "px," + "center " + bgNP2 + "px," + "center " + bgNP3 + "px"; 
+0

То, что вы предлагаете, чтобы просто избавиться от эффекта параллакса для нижнего изображения. Но я не хочу, чтобы это было точно для того, чтобы придерживаться дна: я хочу, чтобы он подходил к другому темпу (например, медленнее, чем прокрутка) и _всего останавливался на дне. – nico

+0

обновил свой ответ –

+0

Извините, если я не понимаю, но что это за 3575 баллов? В любом случае, я добавил вашу модификацию к своей скрипке, [здесь] (https://jsfiddle.net/m89brz60/10/), и кажется, что нижние изображения просто прилипают к основанию, не имея эффекта параллакса ... Я ' d на самом деле воспринимать нижние изображения, идущие медленнее или быстрее, чем прокрутка ... – nico

Смежные вопросы