2017-06-19 33 views
0

首先,感謝您花時間閱讀我的問題。我認爲對於那些更瞭解jQuery/JavaScript的人來說,這是一個簡單的問題。爲jQuery腳本添加偏移

我有一個網頁,當div處於視口的完整視圖中時顯示內容。但是,對我來說,這是令人困惑的。因爲現在,我認爲,它會漸漸消失。

我使用這段代碼:

$(document).ready(function() { 

    /* Every time the window is scrolled ... */ 
    $(window).scroll(function(){ 

     /* Check the location of each desired element */ 
     $('.hideme').each(function(i){ 

      var bottom_of_object = $(this).position().top + $(this).outerHeight(); 
      var bottom_of_window = $(window).scrollTop() + $(window).height(); 

      /* If the object is completely visible in the window, fade it it */ 
      if(bottom_of_window > bottom_of_object){ 

       $(this).animate({'opacity':'1'},1500); 

      } 

     }); 

    }); 

}); 

工作codepen可以在這裏找到link

正如你可以在codepen的div「看看是可見的,當出現比較接近底部的屏幕。這是我想要的,但是現在我的div出現在可能位於視口中心的位置。

我試着通過這樣做$(window).height()-900;來爲$(window).height();添加一些偏移量,但正如預期的那樣,這給了我一個語法錯誤。

下面是HTML和CSS(沒有什麼花哨):

<div id="container"> 
    <article id="content_part_one"> 
     <div class="hideme"> 
      <div class="container"> 
       <div class="row"> 
        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-6"> 
         <h2>Dit is een faketekst</h2> 
          <p>Alles wat hier staat is slechts om een indruk te geven van het grafische effect van tekst op deze plek. Wat u hier leest is een voorbeeldtekst. Deze wordt later vervangen door de uiteindelijke tekst, die nu nog niet bekend is. De faketekst is dus een tekst die eigenlijk nergens over gaat. Het grappige is, dat mensen deze toch vaak lezen. Zelfs als men weet dat het om een faketekst gaat, lezen ze toch door.</p> 
        </div> 
       </div> 
      </div> 
     </div> 
    </article> 
</div> 

#content_part_one {min-height:500px;padding-top:90px;margin-bottom:30px;} 
#container{min-height:2000px;} 
.hideme{opacity:0;} 

所以,真正的問題是,現在我終於淡入內容時div只是在視圖(底部),而不是當它已經處於中心位置時。謝謝您的幫助。

+1

你'div'顯示當'bottom_of_window> bottom_of_object'。替換'top_of_object'上的'bottom_of_object'就像'var top_of_object = $(this).position()。top;'和'if(bottom_of_window> top_of_object){...' –

+0

你的元素總是在屏幕的頂部,所以只要你滾動,當然你的對象的底部會比窗口的底部更大。如果你將它推下窗口,它會像你想要的[CodePen](https://codepen.io/anon/pen/ZyeOaG)一樣淡入。 – George

+0

@AlexeyG優秀。那樣做了!謝謝! –

回答

0

您的代碼中存在拼寫錯誤。

$(window.height()應該$(window).height()