[英]Fading in divs in html using javascript
在我的項目中,我想淡化html中的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).offset().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'},500); } }); }); });
#container { height:2000px; } #container div { margin:50px; padding:50px; background-color:lightgreen; } .hideme { opacity:0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdn.jsdelivr.net/g/jquery.fullpage@2.5.9(jquery.fullPage.min.js+vendors/jquery.easings.min.js+vendors/jquery.slimscroll.min.js)"></script> <link href="https://cdn.jsdelivr.net/jquery.fullpage/2.5.9/jquery.fullPage.min.css" rel="stylesheet" /> <div id="container"> <div>Hello</div> <div>Hello</div> <div>Hello</div> <div>Hello</div> <div>Hello</div> <div>Hello</div> <div class="hideme">Fade In</div> <div class="hideme">Fade In</div> <div class="hideme">Fade In</div> <div class="hideme">Fade In</div> <div class="hideme">Fade In</div> </div>
這可以在這個JS Fiddle中找到在項目中我也使用javascript代碼
$(document).ready(function() {
$('#fullpage').fullpage();
});
這基本上使滾動更好,詳情請訪問https://github.com/alvarotrigo/fullPage.js/
問題:由於整個頁面代碼,函數中的淡入不會進入滾動if條件。
我想你正在尋找像這樣的JS Fiddle 1
JS:
//initialize
var winHeight = $(window).height(),
sections = $('.sections'),
currentSlide = 0;
$('html, body').animate({scrollTop: 0}, 0);
//hide elements not in the view as the page load for the first time
sections.each(function() {
if ($(this).offset().top > winHeight - 5) {
$(this).fadeOut(0);
}
});
//show elements on scroll
$(window).scroll(function(event) {
// retrieve the window scroll position, and fade in the 2nd next section
// that its offset top value is less than the scroll
scrollPos = $(window).scrollTop();
if (scrollPos >= currentSlide * winHeight) {
nextSlide = currentSlide + 2;
$('#sec-' + nextSlide).fadeIn();
// as long as current slide is still in range of the number of sections
// we increase it by one.
if (currentSlide <= sections.length) {
currentSlide++;
}
}
});
更新:
在OP發表評論時“ 我希望部分內的div可以在滾動時淡入而不是部分div而是內部的div,因為有多個 ”,我們需要做的就是改變這一行$(this).fadeOut(0);
到這個$(this).children().fadeOut(0);
然后這一行:
$('#sec-' + nextSlide).fadeIn();
到這個$('#sec-' + nextSlide).children().fadeIn(1500);
而現在,我們正在淡出和淡出該部分的所有孩子 ,而不是該部分本身。
當使用fullPage.js scroll
事件甚至沒有被觸發時,我很驚訝以前的答案得到了這么多的贊成票:D
fullPage.js常見問題解答中詳細介紹了您的問題的解決方案。 這基本上是使用fullPage.js選項scrollbar:true
或autoScrolling:false
。 這樣滾動事件就會被觸發。
如果您仍然希望在從一個部分更改為另一個部分時使用淡入淡出效果,則正確的解決方案是使用fullPage.js回調或fullpage.js狀態類來觸發動畫。 這可以使用javascript或plain css 3來完成。
在本視頻教程中查看有關如何將css3動畫與fullpage.js狀態類結合使用的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.