當(dāng)我們使用a標(biāo)簽做錨點(diǎn)定位的時(shí)候柬祠,如果有做固定頂部導(dǎo)航欄的話禁炒,直接定位到錨點(diǎn)的時(shí)候拾稳,會(huì)發(fā)現(xiàn)定位的位置相較于錨點(diǎn)往下偏移許多肪跋。如下圖:
image.png
image.png
而正常情況我們需要的是這樣的效果:
image.png
image.png
這里用到的方法是:根據(jù)監(jiān)聽瀏覽器的url后面hash值的變化,若有hash值改變則使整個(gè)頁(yè)面向下偏移固定導(dǎo)航欄的高度即可宁炫;頁(yè)面結(jié)構(gòu):
<div class="fixed-wrapper">
<a href="#haveBill" class="target">我是票方</a>
<a href="#haveMoney" class="target">我是資方</a>
</div>
<div class="wrapper haveBill-wrapper" id="haveBill">
<div class="left-dot">我是票方</div>
</div>
<div class="wrapper haveMoney-wrapper" id="haveMoney">
<div class="left-dot">我是資方</div>
</div>
.fixed-wrapper {
position: relative;
width: 100%;
height: 50px;
text-align: center;
top: 0;
left: 0;
line-height: 50px;
background-color: #0094ff;
z-index: 99;
}
上代碼
<script>
window.onload = function () {
// 監(jiān)聽頁(yè)面滾動(dòng)條事件偿曙,避免出現(xiàn)頂部突然塌陷
$(window).scroll(function(){
let scrollTop = $(window).scrollTop();
let height = $('.fixed-wrapper').height();
if(scrollTop > 0) {
$('.fixed-wrapper').css({'position':'fixed'});
$('body').css({'padding-top':height});
}else {
$('.fixed-wrapper').css({'position':'relative'});
$('body').css({'padding-top':0});
}
})
if (("onhashchange" in window) && ((typeof document.documentMode === "undefined") || document.documentMode ==
8)) {
// 瀏覽器支持onhashchange事件
window.onhashchange = hashChangeFire; // TODO,對(duì)應(yīng)新的hash執(zhí)行的操作函數(shù)
} else {
// 不支持則用定時(shí)器檢測(cè)的辦法
setInterval(function () {
var ischanged = isHashChanged(); // TODO羔巢,檢測(cè)hash值或其中某一段是否更改的函數(shù)
if (ischanged) {
hashChangeFire(); // TODO望忆,對(duì)應(yīng)新的hash執(zhí)行的操作函數(shù)
}
}, 150);
}
function hashChangeFire() {
if (location.hash) {
let target = $(location.hash);
if (target.length == 1) {
let top = target.offset().top - $('.fixed-wrapper').height(); // 這里減去的高度為設(shè)置fixed元素的高度
if (top > 0) {
$('html,body').animate({
scrollTop: top
}, 300);
}
}
}
}
}
</script>
已知問題:此方法是根據(jù)hash值變化做的操作,但是當(dāng)我們點(diǎn)擊同一個(gè)錨點(diǎn)兩次的時(shí)候竿秆,hash值并沒有變化也就沒有使得頁(yè)面偏移启摄,所以建議是點(diǎn)擊之后禁用掉當(dāng)前錨點(diǎn);
// 獲取所有的錨點(diǎn)
let targets = document.querySelectorAll('.target');
$('.target').on('click',function(){
// 給當(dāng)前點(diǎn)擊的錨點(diǎn)鏈接添加類名 如果之前點(diǎn)擊過幽钢,阻止事件的觸發(fā)歉备;
if($(this).hasClass('hasClick')){
return false;
}else {
$(this).siblings().removeClass('hasClick');
$(this).addClass('hasClick');
}
})