博主信息
博文 7
粉丝 0
评论 0
访问量 4777
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
0122 【jQuery提升篇】获取滚动值 / 理解scroll事件
小包子的博客
原创
810人浏览过

总结:理解jq的scroll事件,理解scrollTop();

思考:在滚动条每次滚动时都会触发事件,能否在滚动条停止时再触发事件?

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <style>
    *{margin: 0;padding: 0;}
    .banner {height: 500px; text-align: center;}
    .banner img {height: 500px; width: 100%;}
    .top-bar {height: 80px; width: 100%; background: rgba(234,104,162,.6); position: fixed; top: 0; left: 0; padding-top: 20px; box-sizing: border-box; transition: 0.5s;}
    .search-box { width: 300px; margin: 0 auto 0;}
    .search-box input{display: block; float: left; background:none; border: none; box-sizing: border-box;}
    .search-box .search-input{background-color: #fff; height: 30px; padding: 0 10px; border-radius: 20px 0 0 20px; width: 240px;}
    .search-box .submit-input{background-color: #fff; height: 30px; padding: 0 5px; border-radius: 0 20px 20px 0; width: 60px; font-size: 12px; text-align: center; background-color:rgb(234,104,162); color: #fff;}
    .main-body {height: 600px; background-color: #ddd; width: 100%;}

    .scroll-style {height: 40px; padding: 5px;}
    </style>
</head>
<body>
<div class="top-bar">
    <div class="search-box">
        <input type="text" name="search-input" class="search-input">
        <input type="submit" name="submit-input" class="submit-input">
    </div>
</div>
<div class="banner">
    <img src="http://p16.qhimg.com/bdr/__85/t01aedf0a275313a19f.jpg" alt="">
</div>
<div class="main-body"></div>

    
<script>

    $(function () {
        $(window).scroll(function(){
            let bar = $('.top-bar')[0];
            if ($(window).scrollTop() > bar.offsetHeight){
                $('.top-bar').addClass('scroll-style');
            } else {
                $('.top-bar').removeClass('scroll-style');
            }
            console.log($(window).scrollTop());
        });
    });
</script>


</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学