[英]Show div tag after scrolling 100px from in Vue
我正在工作 filename.vue 文件。 我正在嘗試添加一個 div 以在滾動 100px 后顯示。 我無法得到它。 請幫我找出我哪里出錯了。
<template>
<div id="sectionTop">
<div id="scrollButton">
<a class="topButton" href="javascript:document.getElementById('sectionTop').scrollIntoView(true);"><img src="../../images/uparrow.svg"></a>
</div>
</div>
</template>
<script>
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.scrollButton').fadeIn();
} else {
$('.scrollButton').fadeOut();
}
});
</script>
根據建議更新
<template>
<div id="sectionTop">
<div id="scrollButton">
<a class="topButton" href="javascript:document.getElementById('sectionTop').scrollIntoView(true);" v-if="scrollpx > 800"><img src="../../images/uparrow.svg"></a>
</div>
</div>
</template>
<script>
export default {
data() {
return {
scrollpx: 0
};
},
methods: {
handleScroll() {
this.scrollpx = window.scrollY;
}
},
created() {
window.addEventListener('scroll', this.handleScroll);
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
}
};
</script>
您不需要 jquery 來執行此操作。 您可以在 vue 組件的created
方法中為滾動事件注冊一個事件偵聽器(之后不要忘記取消注冊!)。 在handleScroll
方法中,您可以更新保存當前 scrollY 值的變量。 現在這個值可用於 vue 並且可以“被動地”使用。 例如,您可以使用v-if
顯示您的按鈕:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="replace"></div> <script> new Vue({ el: '#replace', template: ` <div id="scroller"> <div id="sectionTop" style="height: 5000px"> Please Scroll down <div id="scrollButton"> <a class="topButton" style="position:fixed" v-if="scrollpx > 800">Scroll top</a> </div> </div> </div>`, data() { return { scrollpx: 0 }; }, methods: { handleScroll() { this.scrollpx = window.scrollY; } }, created() { window.addEventListener('scroll', this.handleScroll); }, destroyed() { window.removeEventListener('scroll', this.handleScroll); } }) </script>
這就是我解決這個問題的方法。
<a class="scrollTop" href="javascript:document.getElementById('sectionTop').scrollIntoView(true);" title='Click here to go to the top' v-if="scrollpx > 100"><img src="../../images/uparrow.svg"></a>
<script>
export default {
data() {
return {
scrollpx: 0
};
},
methods: {
handleScroll() {
this.scrollpx = document.body.scrollTop;
}
},
mounted() {
document.body.addEventListener('scroll', this.handleScroll);
}
};
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.