html:
<div id="nav" >
<a class="xdapai" data-id="dapai" @click="goscrol">大牌</a>
<a class="xdianfeng" data-id="dianfeng" @click="goscrol">巅峰</a>
<a class="xbaokuan" data-id="baokuan" @click="goscrol">爆款</a>
</div>
js:
methods: {
goscrol($event) {
var id = $event.target.dataset.id;
var $scrollHeight = $("#" + id).offset().top;
$("html, body").animate(
{
scrollTop: $scrollHeight
},
500
);
},
},
mounted() {
//导航栏操作,当导航栏滚动到顶部,即导航栏吸附在顶部不动。
window.onload = function() {
var arr = [
{ id: "dapai", height: $("#dapai").height() },
{ id: "dianfeng", height: $("#dianfeng").height() },
{ id: "baokuan", height: $("#baokuan").height() },
{ id: "freexi", height: $("#freexi").height() },
{ id: "fuli", height: $("#fuli").height() }
];
//兼容性
var box = document.getElementById("nav");
var topmargin = box.offsetTop;
var userAgent = navigator.userAgent.toLowerCase();
var isIphone = userAgent.match(/iphone os/i) == "iphone os";
var isAndroid = userAgent.match(/android/i) == 'android';
$(window).on("scroll", function() {
var scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if(isIphone){
scroll >= topmargin - 50 ? $("#nav").addClass("postplayIOS") : $("#nav").removeClass("postplayIOS");
}else{
scroll >= topmargin - 50 ? $("#nav").addClass("postplayAndroid") : $("#nav").removeClass("postplayAndroid");
}
//当导航栏离开顶部时,对应的导航选中样式消失
if (document.getElementById(arr[0].id).offsetTop - $(window).scrollTop() > 90 ) {
$(".x" + arr[0].id).removeClass("redfont");
}
for (var i = 0; i < arr.length; i++) {
var nowbox = document.getElementById(arr[i].id);
if (nowbox.offsetTop - $(window).scrollTop() < 90) {
$(".x" + arr[i].id).addClass("redfont").siblings().removeClass("redfont");
}
}
});
};
}
css:
#nav {
background: #f37938;
display: flex;
100%;
}
#nav a {
display: block;
20%;
height: 39px;
line-height: 39px;
text-align: center;
color: #fff;
}
.postplayIOS {
position: sticky;
position: -webkit-sticky;
left: 0;
top: 0;
}
.postplayAndroid {
position: fixed;
left: 0;
top: 0;
}
#nav .redfont {
border-bottom: 2px solid #f9f100;
}