我有这个JS代码:
$(document).scroll(function(e) {
var scrolltop = $(window).scrollTop();
var mindist = 1000;
var closest = '';
$('#header').each(function(i, el){
var thisdist = Math.abs(scrolltop - $(el).offset().top);
if (thisdist < mindist) {
closest = el.id;
mindist = thisdist;
}
});
if (closest != '') {
$('#header').toggleClass('test');
}
});
和我的HTML:
<div id="header">
<img src="header.png" width="100%" style="max-width:1024px;" />
</div> <!-- header-topbar -->
当用户开始向下滚动页面时,我希望标题的高度更小,图像也更小。
我在CSS中尝试了这个:
.test {
height: 100px;
}
但它根本不会改变高度。
答案 0 :(得分:2)
试试这个:
CSS:
<style>
.test img {
height: 100px;
background-color: #ccc;
position: fixed;
top: 0;
}
</style>
HTML:
<div id="header">
<img src="header.png" width="100%" style="max-width:1024px;" />
<p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p><p>this is a simple text</p>
</div> <!-- header-topbar -->
JS:
<script>
$(document).scroll(function(e) {
$(window).scrollTop() > 100 ? $('#header').addClass('test') : $('#header').removeClass('test');
});
</script>
答案 1 :(得分:0)
试试这个:使用计时器功能知道滚动开始和停止的时间
(function() {
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
$('#header').addClass("test");// set height to 100px
timer = setTimeout( refresh , 15000 );
});
var refresh = function () {
$('#header').removeClass("test");
};
})();
答案 2 :(得分:0)
这是我的完整解决方案:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style>
html,body{
width:100%;
height:100%;
border:0px;
margin:0px;
padding:0px;
}
body{
position:relative;
overflow:hidden;
}
#wrap{
width:100%;
height:100%;
position:relative;
overflow-y:auto;
display:inline-block;
}
.test{
height: 100px;
display:block;
overflow:hidden;
}
</style>
<script>
var position = 0;
function redraw()
{
var height=$('#body').height();
if(position>0)
{
$('#header').toggleClass('test',true);
}
console.log(position); // see the output on the developer tool console
}
</script>
</head>
<body>
<div id="wrap">
<div id="header">
<img src="header.png" width="100%" style="max-width:1024px;" />
</div> <!-- header-topbar -->
<br />
<br />
... <!-- put as many break tags as you can to test it -->
<br />
<br />
</div>
<script>
position = $('#wrap').scrollTop();
$(document).ready(function()
{
$('#wrap').scroll(function()
{
var scroll = $('#wrap').scrollTop();
setTimeout('redraw()',5);
position = scroll;
});
});
</script>
</body>
</html>
使用setTimeout()
获取滚动位置的实时值。
另外,请使用toggleClass(className)
。
toggleClass(className,switch)