2017-06-14 68 views
0

我正在使用此腳本來隱藏div並在滾動頁面中的某個點時顯示它。這工作正常,但當我回滾到頂部時,div仍然可見。任何人都可以幫我修改一下我可以對代碼進行的修改,以便在滾動到期望點之上時再次隱藏div。在滾動點後顯示並隱藏div

感謝,T

$(document).ready(function() { 
$("#dvid").hide(); //hide your div initially 
var topOfOthDiv = $("#othdiv").offset().top; 
$(window).scroll(function() { 
    if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div? 
     $("#dvid").show(); //reached the desired point -- show div 
    } 
}); 
}); 

回答

0
$(document).ready(function() { 
    $("#dvid").hide(); //hide your div initially 
    var topOfOthDiv = $("#othdiv").offset().top; 
    $(window).scroll(function() { 
     if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div? 
      $("#dvid").show(); //reached the desired point -- show div 
     } 
     else{ 
      $("#dvid").hide(); //else above the desired point -- hide div 
     } 
    }); 
}); 
+0

奇拉格拉溫德拉太謝謝你了:) –

+0

你是最歡迎的。如果它回答你的問題,請接受答案:) –

0

首先,檢查元素的可見性:

var rect = element.getBoundingClientRect(); 
var visible = Boolean(
    rect.top >= 0 
    && rect.left >= 0 
    && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) 
    && rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
); 

然後綁定事件重新驗證的可視性:

jQuery(window).bind('DOMContentLoaded load resize scroll', fn); 
// fn - is your function to show/hide elements in accordance with previous statement 

所以,最終代碼將是:

$(document).ready(function() { 
    var checkVisibility = function() { 
     $("#dvid, #othdiv").each(function() { 
      var rect = this.getBoundingClientRect(), 
       visible = Boolean(
        rect.top >= 0 
        && rect.left >= 0 
        && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) 
        && rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
       ); 
      $(this)[visible ? 'show' : 'hide'](); 
     }); 
    }; 
    //hide your divs initially 
    $("#dvid, #othdiv").hide(); 
    jQuery(window).bind('DOMContentLoaded load resize scroll', checkVisibility); 
}); 
0
$(document).ready(function() { 
$("#dvid").hide(); //hide your div initially 
var topOfOthDiv = $("#othdiv").offset().top; 
$(window).scroll(function() { 
    if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div? 
     $("#dvid").show(); //reached the desired point -- show div 
    } else { 
     $("dvid").show(); //hide div 
    } 
}); 
});