vue 中固定導航欄的實例代碼
更新時間:2019年11月01日 10:33:54 作者:徹夜不歸
今天小編就為大家分享一篇vue 中固定導航欄的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
點擊按鈕回頂
<template lang="html">
<div class="gotop-box">
<i @click="gotop"class="icon topIcon"></i>
</div>
</template>
<script>
export default {
methods: {
gotop: function () { // 點擊回頂按鈕 返回頂部
setTimeout(()=>{
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
},1000)
}
}
}
window.onscroll = function() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const goTop= document.querySelector('.gotop-box')
if (scrollTop >200) {
goTop.style.display = 'block'
} else {
goTop.style.display = 'none'
}
}
</script>
<style lang="css">
.topIcon {
position: fixed;
bottom: 5rem;
right: 1rem;
width: 2rem;
height: 2rem;
border-radius: 50%;
background:url(../assets/images/gotop.png)center center no-repeat;
background-size: cover;
}
</style>


固定導航欄案例
<template>
<div>
<div id="topPart">頂部距離</div>
<div id="navBar" :class="{isFixed:istabBar}">固定導航欄</div>
<div id="mainPart">
<ul>
<li>內容部分</li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</template>
<script>
export default {
data () {
return {
istabBar: false
}
},
methods: {
// 添加一個方法 兼容
handleScroll () {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
// 固定導航欄
let topBar = document.querySelector("#topPart");
let navBar = document.querySelector("#navBar");
let mainPart = document.querySelector("#mainPart");
if (scrollTop > topBar.offsetHeight){
this.istabBar = true
mainPart.style.paddingTop = navBar.offsetHeight + "px";
} else {
this.istabBar = false
mainPart.style.paddingTop = "0px";
}
}
},
mounted () {
window.addEventListener('scroll', this.handleScroll); // Dom樹加載完畢
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll) // 銷毀頁面時清除
}
}
</script>
<style>
#topPart{
width: 100%;
height: 100px;
background-color: yellow;
}
.isFixed {
position: fixed;
top: 0;
z-index: 10;
}
#navBar {
width: 100%;
height: 50px;
background-color: red;
}
#mainPart {
width: 100%;
}
#mainPart ul {
width: 100%;
}
#mainPart ul li {
width: 100%;
height: 40px;
background-color: orange;
margin-bottom: 10px;
}
</style>

以上這篇vue 中固定導航欄的實例代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue2中,根據(jù)list的id進入對應的詳情頁并修改title方法
今天小編就為大家分享一篇vue2中,根據(jù)list的id進入對應的詳情頁并修改title方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
如何使用VuePress搭建一個類型element ui文檔
這篇文章主要介紹了如何使用VuePress搭建一個類型element ui文檔,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-02-02

