设置div在窗口滚动位置较大时不显示
问题描述:
当窗口滚动位置大于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>
答
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>
答
img_top
是一个对象,因为
$("#head").offset();
返回*的对象和左偏移, 你必须使用
$("#head").offset().top
在你的计算
噢,现在我记得什么是失踪。谢谢,我很快就会接受这个答案 – Reece