javascript - 滚动时更改 div 样式

标签 javascript jquery html css

我有这个 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/

相关文章:

javascript - div 中垂直居中图像

javascript - 如何将文件对象呈现为 HTML 元素(使用 Vue.js)

javascript - 上传前普通 javascript 预览视频文件 - 无 JQUERY

javascript - 如何在没有 npm require 的情况下使用 ReactRouter CDN 方式?

php - 优化 JavaScript CSS 下载

javascript - 在 React Native 中重新渲染 - 问题

javascript - 解析angular2中的xml以在 View 中呈现

javascript - 如何找到所有具有特定值的输入元素?

javascript - 如何检测浏览器何时放置保存的密码?

javascript - jQuery 添加额外的变量到 url