2017-06-15 76 views
0

當窗口滾動位置大於div的底部位置時,我需要隱藏div。我試圖自己做,但我做錯了什麼。還有另一個問題,因爲我需要更好的代碼與文本比率來提交此問題。爲什麼當我alert(); img_top它說對象對象?設置div在窗口滾動位置較大時不顯示

$(document).ready(function(){ 
 
\t var img_height = $("#head").outerHeight(); 
 
\t var img_top = $("#head").offset(); 
 
    var img_bot = img_height + img_top; 
 

 
    $(window).scroll(function(){ 
 
    \t var wind_pos = $(window).scrollTop(); 
 
    \t $("p").html(wind_pos); 
 
    
 
    if(wind_pos > img_bot){ 
 
    \t $("#head").addClass("hide"); 
 
    } 
 
    }); 
 
});
*{ 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
body{ 
 
    height: 4000px; 
 
} 
 

 
#head{ 
 
    height: 600px; 
 
    background-color: blue; 
 
} 
 

 
.hide{ 
 
    display: none; 
 
} 
 

 
p{ 
 
    background-color: yellow; 
 
    width: 100%; 
 
    height: 50px; 
 
}
<div id="head"> 
 

 
</div> 
 
<p> 
 
</p> 
 
<script 
 
    src="https://code.jquery.com/jquery-3.2.1.min.js" 
 
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
 
    crossorigin="anonymous"></script>
表示匹配元素的位置

回答

1

jQuery.offset()返回的對象,你想讀的是top財產。

$(document).ready(function() { 
 
    var img_height = $("#head").outerHeight(); 
 
    var img_top = $("#head").offset().top; 
 
    var img_bot = img_height + img_top; 
 

 
    $(window).scroll(function() { 
 
    var wind_pos = $(window).scrollTop(); 
 
    $("p").html(wind_pos); 
 

 
    if (wind_pos > img_bot) { 
 
     $("#head").addClass("hide"); 
 
    } 
 
    }); 
 
});
* { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
body { 
 
    height: 4000px; 
 
} 
 

 
#head { 
 
    height: 600px; 
 
    background-color: blue; 
 
} 
 

 
.hide { 
 
    display: none; 
 
} 
 

 
p { 
 
    background-color: yellow; 
 
    width: 100%; 
 
    height: 50px; 
 
}
<div id="head"> 
 

 
</div> 
 
<p> 
 
</p> 
 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

+0

噢,現在我記得什麼是失蹤。謝謝,我很快就會接受這個答案 – Reece

1
img_top 

是一個對象,因爲

$("#head").offset(); 

返回頂級的對象和左偏移, 你必須使用

$("#head").offset().top 

在你的計算