一、簡單吸頂
思路:需要寫兩個樣式,一個吸頂樣式,一個正常樣式,通過監聽scroll事件,實現吸頂功能
//fix_info_title爲吸頂樣式通過固定定位實現,info_title爲正常樣式
<div :class="isceiling?'fix_info_title':'info_title'">
<span @click="goproinfo(0)" :class="iscolor1?'proinfo_span':''">商品詳情</span>
<span @click="goproinfo(1)" :class="iscolor2?'params_span':''">規格參數</span>
<span @click="goproinfo(2)" :class="iscolor3?'evaluate_span':''">用戶評價</span>
<button class="fix_shoppingCart" v-show="isceiling">加入購物車</button>
</div>
mounted(){
window.addEventListener("scroll",this.celling) //監聽scroll事件
this.$nextTick(function () {
window.addEventListener('scroll', this.onScroll)
})
}
//吸頂
celling(){
//獲取需要出現吸頂的位置
let titletop=document.getElementsByClassName('info_title_div')[0].offsetTop
//獲取鼠標位置
let bodytop=document.body.scrollTop || document.documentElement.scrollTop;
this.isceiling=bodytop>titletop //true/false
},
二、根據位置標題的樣式發生變化
比如,鼠標滑動到商品詳情頁面具體內容時,商品詳情四字變爲紅色,其他爲灰色
//滾動
onScroll(){
let bodytop=document.body.scrollTop || document.documentElement.scrollTop;
let getinfo=document.querySelector('.info_title1').offsetTop //獲取商品詳情div的高度
let getparams=document.querySelector('.info_title2').offsetTop //獲取規格參數div的高度
let getevaluate=document.querySelector('.info_title3').offsetTop //獲取用戶評論div的高度
if(bodytop<=getparams-70){
this.iscolor1=true
this.iscolor2=false
this.iscolor3=false
}else if(bodytop>=getparams-70 && bodytop<=getevaluate-70){
this.iscolor1=false
this.iscolor2=true
this.iscolor3=false
}else if(bodytop>=getevaluate-70){
this.iscolor1=false
this.iscolor2=false
this.iscolor3=true
}
}
三、點擊吸頂的標題,跳轉到對應位置
//點擊標題跳轉
goproinfo(index){
let getinfo=document.querySelector('.info_title1').offsetTop //獲取商品詳情div的高度
let getparams=document.querySelector('.info_title2').offsetTop //獲取規格參數div的高度
let getevaluate=document.querySelector('.info_title3').offsetTop //獲取用戶評論div的高度
let bodytop=document.body.scrollTop || document.documentElement.scrollTop;
if(index==0){
let distance1=getinfo-110
// document.documentElement.scrollTop=getinfo-110
$('html,body').animate({scrollTop: distance1}, 1000);
}else if(index==1){
let distance2=getparams-60
// document.documentElement.scrollTop=getparams-60
$('html,body').animate({scrollTop: distance2}, 1000);
}else if(index==2){
let distance3=getevaluate-60
$('html,body').animate({scrollTop: distance3}, 1000);
}
},
注:可以使用jq提供的方法,使得頁面有動畫效果
$('html,body').animate({scrollTop: 需要到達的位置}, 時間(ms));
四、在vue中使用jq
安裝 npm install jquery
在需要使用jq的.vue文件中導入
import $ from 'jquery'