js实现百度搜索框滑动固定顶部
程序员文章站
2022-07-01 18:59:42
...
现在很多主流系统例如百度、有道、爱奇艺等的搜索框都有一个特点,滑动到刚好看不到搜索框时,固定搜索框到顶部,这也算是一个对用户友好型的操
作。
在看了百度的js和css后自己摸索出来实现效果,还是学艺不精,没读懂百度的js,有点小bug。
实现效果
作。
在看了百度的js和css后自己摸索出来实现效果,还是学艺不精,没读懂百度的js,有点小bug。
<!DOCTYPE html> <html> <head> <title>柳絮飞祭奠</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <style type="text/css"> div input { width: 538px; height: 38px; border: 1px solid #b8b8b8; border-bottom: 1px solid #ccc; } .z_s_top_wrap_fix { position: fixed; top: 0; left: 0; width: 100%; height: 70px !important; padding-top: 20px; background-color: #fff; box-shadow: 0 0 3px 3px #e6e6e6; z-index: 2; } .z_s_wr_fix { margin: auto; width: 641px; margin-top: 0 !important; margin-bottom: 100px; } </style> </head> <body> <div class="z_s_top_wrap" id="z_s_top_wrap"> <div style="margin:auto;width:1024px;height: 30px;"> <input id="txt_search_ipt" type="text" style="float: left;"><input type="button" style="height: 42px;float: left;background-color: #388cff;width: 103px;" value="百度一下"> </div> </div> <div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div> <div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div> <div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div> <div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaa</div> </body> <script type="text/javascript" src="../plugins/angular/angular.js"></script> <script type="text/javascript" src="../plugins/jquery/jquery.min.js"></script> <script type="text/javascript"> window.onscroll = function() { //获取搜索框当前距离顶部位置document.getElementById("z_s_wraa").offsetTop //获取滚动条离浏览器顶部位置window.pageYOffse if (document.getElementById("txt_search_ipt") == undefined) { return false; } if ($(document).scrollTop() + 30 >= $(document).height() - $(window).height()) { $("body").height($("body").height() + 20); } if ((document.getElementById("txt_search_ipt").offsetTop - window.pageYOffset) < 0) { //2.2.添加class固定搜索框到顶部 $("#z_s_top_wrap").addClass("z_s_top_wrap_fix"); $(".z_s_wr").addClass("z_s_wr_fix"); $("body").height($("body").height() - 20); } else { //2.3.移除搜索框固定 $("#z_s_top_wrap").removeClass("z_s_top_wrap_fix"); $(".z_s_wr").removeClass("z_s_wr_fix"); } }; </script> </html>
实现效果