2014-08-30 59 views
0

我正在製作一個自定義的視差背景JavaScript。在這一點上,它很好(正如預期的那樣)。不幸的是,我是JavaScript新手,所以我的知識是有限的。當我只需要一個實例時(這是它的寫法),我寫的腳本效果很好。 我希望它能夠處理多個實例。JavaScript的視差功能 - 如何創建多個實例

現在,它找到類0123¾的元素,這是否有魔力。顯然,按照它的寫法,擁有多個「視差」類的實例/元素將不起作用。我完全難以接受如何進行下一步並將我的功能分別應用於所有實例。我搜索了很多,但仍然不知道如何繼續。 代碼已附加。最終,我將爲$(document).ready,$(window).resize$(window).scroll製作一個單獨的功能,以節省處理能力,但我不想這樣做直到我接近終點線。

如何格式化此腳本以處理多個實例(網頁的多個部分將使用該腳本作爲效果)?

<!DOCTYPE html> 
<html lang="en"> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0"/> 
<title>Test Page</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
</head> 
<body> 
<script> 
    $(document).ready(function(){ 
    parallaxReady(); 
    }); 

    $(window).resize(function(){ 
    parallaxReady(); 
    }); 

    $(window).scroll(function(){ 
    parallaxReady(); 
    }); 
    function parallaxResize() {} 
    function parallaxScroll() {} 
    function parallaxReady() {    
     $(".parallax img").width('100%');            // This is for window resizing 
     $(".parallax img").height('auto');            // This is for window resizing 
     var winHeight = window.innerHeight;            // 
     var offset = $(".parallax").offset();           // 
     var fromTop = offset.top;              // 
     var scrollPos = window.pageYOffset;            // 
     var ratio = -.7;                // I would like to set this individually 
     var verticalAlign = 0;               // 
     var travel = 0;                 // 
     var containerHeight = $(".parallax").css("height");        // Get container height 
     var containerWidth = $(".parallax").css("width");        // Get container width 
      containerHeight = parseInt(containerHeight, 10);       // Remove px 
      containerWidth = parseInt(containerWidth, 10);        // Remove px 
     var imageHeight = $(".parallax img").css("height");        // Get image height 
     var imageWidth = $(".parallax img").css("width");        // Get image width 
      imageHeight = parseInt(imageHeight, 10);         // Remove px   
      imageWidth = parseInt(imageWidth, 10);          // Remove px 

     if (winHeight > containerHeight){            // If the container is smaller than Viewport 
      travel = (winHeight - containerHeight);          // Set travel distance 

      if (imageHeight < (containerHeight + (travel * -ratio))){     // If image is too short 
       $(".parallax img").height(containerHeight + (travel * -ratio) + 'px'); // Resize image to height needed 
       imageHeight = (containerHeight + (travel * -ratio));     // Update variable 
       $(".parallax img").width('auto');          // Set image width to auto 
       imageWidth = $(".parallax img").css("width");       // Update variable 
       imageWidth = parseInt(imageWidth, 10);         // Remove px 
       } 
      else { 
       verticalAlign = (imageHeight - (containerHeight + (travel * -ratio))) // Else if image is tall enough, center it vertically 
       }      
      } 
     else {                   // Else if container is taller than Viewport 
      travel = (containerHeight) - winHeight;          // Set travel distance 
      $(".parallax img").height(winHeight + (travel * -ratio) + 'px');   // Resize image to height needed 
      $(".parallax img").width('auto');           // Set image width to auto 
      imageWidth = $(".parallax img").css("width");        // Update variable 
      imageWidth = parseInt(imageWidth, 10);          // Remove px 

      if (imageWidth < containerWidth){           // If image width is too short 
       $(".parallax img").width(containerWidth);        // Set image width to 100% container width 
       $(".parallax img").height('auto');          // Set height to auto 
       verticalAlign = (imageHeight - (winHeight + (travel * -ratio)))   // Center it vertically 
       } 
      }   

     if (imageWidth > containerWidth){            // If image width is wider than container 
      $(".parallax img").css('left',((imageWidth - containerWidth) * -.5) + 'px');// Center image horizontally 
      } 
     else {                   // Else if image is not wider than container 
      $(".parallax img").css('left','0');           // Reset to 0 
      } 

     var alignment = ((fromTop - winHeight) + containerHeight);      // The initial height reference for image 

     var newPos = (scrollPos * ratio) - ((alignment * ratio) + (verticalAlign *.5)); // Position for Image based on our criteria 
     $(".parallax img").css('bottom',newPos + 'px');         // Set the new position for image 

     $("#debug").text("Scroll Height: " + scrollPos + " | Window Height: " + winHeight + " | DIV Height: " + containerHeight + " | Image Height " + imageHeight + " | Offset: " + fromTop + " | Travel: " + travel + " | Alignment: " + alignment + " | Vertical Align: " + verticalAlign); 
     } 
</script> 
<style scoped> 
html, body {padding:0;margin:0;font-family:Arial, Helvetica, sans-serif;} 
#debug {padding:15px;background:#000;font-size:12px;color:#fff;position:fixed;top:0;left:0;z-index:1000;opacity:.5;} 
.spacer {height:70vh;background: #444;} 
.longer {height:100vh;} 
.parallax {overflow:hidden;position:relative;} 
.parallax img {width:100%;position:absolute;bottom:0;} 
.parallax div {width:40%;margin:10% auto;padding:5%;position:relative;color:#fff;font-size:36px;text-align:center;background:rgba(0,0,0,0.2);} 
.parallax div p {padding:10px 0;margin:0;font-size:15px;text-align:justify;} 
</style> 
    <div class="spacer"></div> 
    <div class="parallax"> 
     <img alt="parallax" src="http://www.wallpaperup.com/uploads/wallpapers/2012/09/21/15744/3ad1c548edfc58f499feda5b042fb857.jpg"> 
     <div> 
      This is Random Text 
      <p>Lorem ipsum dolor sit amet, mel id errem fierent sensibus, liber similique voluptatibus sit te, cum ea aliquip persequeris. Eam ne hinc labitur suscipit. Te laudem scaevola sea, esse nibh maiorum quo te. Sit enim regione ei, pro te accusamus definitiones. Maiorum perpetua oportere pro eu. Ea mel homero inermis insolens, ut adhuc putent qui.</p> 
      <p>Apeirian platonem interpretaris eu quo, wisi audire appetere sea ad. Vis cibo congue libris ut, has ea erat maiorum percipitur. Ius ut doming inciderint, affert eirmod cu sed. Ne mel falli partiendo, ei agam minim legimus sit. Quem omnis mundi pro in, ei viderer mediocritatem quo.</p> 
     </div> 
    </div> 
    <div class="spacer longer"></div> 
    <div id="debug"></div> 
</body> 
</html> 
+0

請撥打您的密碼。 – ProllyGeek 2014-08-31 00:19:36

+0

OP當然應該擺弄它,但來吧,這隻需要我45秒來擺弄:http://jsfiddle.net/pabo/L2Lhz8vp/ – pabo 2014-08-31 00:27:13

回答

0

我喜歡這個效果!在JavaScript中有幾個常見的模式來做這樣的模塊。一種方法如下。

讓你div.​​parallax要求,像所有的一切外容器:

<div class='parallax'> 
    content 
</div> 

做一個parallax 「類」。在JavaScript中,「class」只是一個遵循特定模式的對象。這將是暴露於全球範圍的唯一對象。你的parallaxReady()函數已經危險地接近它(這很好)。

製作parallax.init()或類似的東西。該函數將接受options散列。你會調用該函數的每個視差格在頁面上是這樣的:

$('div.parallax').forEach(function(element) { 
    parallax.init({ 
     element: element, 
     image: "/path/to/my/image.jpg", 
    }); 
}); 

重寫你的代碼parallax.init()。任何你現在正在引用的地方$(".parallax")$(".parallax img")或任何會改變,以引用傳入的動態元素。例如,該行:

$(".parallax img").width('100%'); 

將改變到

options.element.width('100%'); 

parallax.init()將產生的視差div容器內所需的任何其它元件 - 如圖像DIV,間隔件,不管。它也會設置它需要的變量和東西,然後註冊一個滾動事件。看起來你現在在parallaxReady中的大部分代碼都會在parallax.init()中的這個滾動事件中結束。

parallax.init()也可以返回某種標識符,以便您可以使用它來調用parallax.stop(),如果您實現了。或者你可以把這整個事情做成一個實際的jQuery插件。

我希望能幫助你開始。

+0

嘿@pabo,謝謝你的回覆!我喜歡你要去的地方...我一天大部分時間都會離開,但當我回來的時候,我會爲你提供一些問題/想法。 – GabeNix 2014-08-31 14:07:49