总结:理解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>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号