導航欄滾動
在專案,遇到導航欄滾動,滾到到視窗頂部懸停;滾動導航欄的產品,對應的導航欄選中。
html:
<div id="nav" >
<a class="xyifu" data-id="yifu" @click="goscrol">衣服</a>
<a class="xxiezi" data-id="xiezi" @click="goscrol">鞋子</a>
<a class="x
</div>
<div id="yifu">衣服列表</div>
<div id="xiezi">鞋子列表</div>
<div id="maozi">帽子列表</div>
js:
//點選對應的導航欄,跳轉到對應商品列表
goscrol($event) {
var id = $event.target.dataset.id;
var $scrollHeight = $("#" + id).offset().top
$("html, body").animate(
{
scrollTop: $scrollHeight
},
500
);
},
window.onload = function() {
var arr = [
{ id: "yifu", height: $("#yifu").height() },
{ id: "xiezi", height: $("#xiezi").height() },
{ id: "maozi", height: $("#maozi").height() }
];
var box = document.getElementById("nav");
var topmargin = box.offsetTop;
//不同裝置,安卓,iphone
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:
.postplayIOS {
position: sticky;
position: -webkit-sticky;
left: 0;
top: 0;
}
.postplayAndroid {
position: fixed;
left: 0;
top: 0;
}
#nav .redfont {
border-bottom: 2px solid #f9f100;
}