我有这个 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;
}
但它根本不会改变高度。
最佳答案
试试这个:
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>
关于javascript - 滚动时更改 div 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23674303/