在做导航栏时除了用我们熟悉的html和css来布局以外,还需要用到jquery中scrolltop和scrollleft知识,它们主要用于设置或者获取垂直滚动条的位置,根据页面被卷曲的高度来固定导航栏位置,接下来在文章中将和大家详细分享。
scrolltop
返回或设置匹配元素的滚动条的垂直位置。
$(selector).scrolltop(offset)
offset : 规定相对滚动条顶部的偏移,以像素为单位,可以写也可以不写
例: 获取页面被卷曲的高度
$(window).scrolltop();
scrollleft
返回或设置匹配元素的滚动条的水平位置。
水平位置指的是从其左侧滚动过的像素数,
当滚动条位于最左侧时,位置是 0。
$(selector).scrollleft(position)
position:规定以像素计的新位置,可以写也可以不写
滚动条的水平位置指的是从其左侧滚动过的像素数。当滚动条位于最左侧时,位置是 0。
例:获取页面被卷曲的宽度
$(window).scrollleft();
案例分享:固定百度搜索栏
<!doctype html><html><head><meta charset="utf-8"><title>document</title><style>*{padding:0;margin:0;}.all{width:100%;height:2000px;}.box{width:100%;height:75px;background-color: #fff;border: 1px solid #ccc;position: relative;}.sousu-left img{position: absolute;top:20.5%;left:28.45%;}.box1{width:536px; height: 41px; border:1px solid #ccc; margin:16px auto; }.sousu-right span{width:140px;height:41px;border:1px solid #ccc;color:#fff;background-color:rgb(51,136,255);text-align: center;line-height: 41px;font-size:14px;position: absolute;right:28.64%;top:19.69%; } .fixed{ position: fixed; left:0; top:0; }</style></head><body><div><div><!-- 定义左边和右边两个盒子 --><div><img src="images/logo_top_86d58ae1.png"><div></div></div><div><span>百度一下</span></div></div></div><script src="jquery/jquery-1.12.4.js"></script><script>$(function(){$(window).scroll(function(){if($(window).scrolltop()>=$(".box").height())判断当卷曲的高度大于box高度时给box添加一个fixed属性,使它固定在顶部{$(".box").addclass("fixed");}else{$(".box").removeclass("fixed");如果小于则移除class属性}})})</script></body></html>
总结:以上就是本篇文章的全部内容了,希望通过这个案例大家对scrolltop和scrollleft的应用更加清楚
以上就是如何通过jquery在页面中固定导航栏的详细内容。
