export default { data() { return { goodsId: " ", goodsData: [], current: 0, oldScrollTop: 0, scrollTop: 0, searchBgc: " rgba(0, 0, 0, 0.1)", show: false, opacity: 0, flag: true, }; }, mounted() { this.handleScroll(); }, beforeDestroy() { window.removeEventListener("scroll", this.handleScrollFn); //离开当前组件别忘记移除事件监听哦 }, watch: { scrollTop: { handler: function (newValue, oldValue) { clearTimeout(this.timer); this.timer = setTimeout(() => { if (newValue == window.scrollY) { this.oldScrollTop = newValue; if (this.oldScrollTop > 100) { this.show = true; } else { this.show = false; } } else { if (this.oldScrollTop == oldValue) { // console.log("滚动开始"); } } }, 20); }, immediate: true, }, }, methods: { handleScroll() { this.handleScrollFn = () => { this.scrollTop = window.scrollY; }; window.addEventListener("scroll", this.handleScrollFn); }, onClickLeft() { this.$router.go(-1); }, onChange(index) { this.current = index; }, returnFn() { this.$router.go(-1); }, // 加入购物车 joinShopCar() { alert("加入购物车成功"); let shopcarList = JSON.parse(localStorage.getItem("shopcar")) || []; console.log(shopcarList); this.goodsData.num = 1; this.goodsData.isChecked = false; let ind = shopcarList.findIndex((ele) => { return ele.id == this.goodsId; }); console.log(ind); // 如果有相同的返回该数据的下标,没有则返回-1 if (ind != -1) { shopcarList[ind].num++; } else { shopcarList.push(this.goodsData); } localStorage.setItem("shopcar", JSON.stringify(shopcarList)); this.$router.push("/shopcar"); }, // 立即结算 payFn() { localStorage.setItem("goodspay", JSON.stringify(this.goodsData)); this.$router.push("/pay"); }, }, async created() { this.goodsId = this.$route.query.id; try { let { data } = await getGoodsDetailApi(this.goodsId); this.goodsData = data.data.goodsData; console.log(this.goodsData); } catch (err) { console.log(err); } }, };怎么给页面滚动事件加个背景颜色淡入淡出
时间: 2024-01-30 21:03:12 浏览: 58
你可以在 `data` 中添加一个变量 `searchBgc` 来控制搜索栏背景颜色,然后在 `watch` 中监听 `scrollTop` 的变化,当 `scrollTop` 大于 100 时,将 `searchBgc` 设置为需要的颜色值,同时设置 `opacity` 为 1,实现淡入效果;当 `scrollTop` 小于等于 100 时,将 `searchBgc` 设置为另一个颜色值,同时设置 `opacity` 为 0,实现淡出效果。具体代码如下:
```javascript
export default {
data() {
return {
// 其他变量...
searchBgc: "rgba(0, 0, 0, 0.1)",
opacity: 0
};
},
watch: {
scrollTop: {
handler(newValue, oldValue) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
if (newValue == window.scrollY) {
this.oldScrollTop = newValue;
if (this.oldScrollTop > 100) {
this.show = true;
this.searchBgc = "rgba(0, 0, 0, 0.6)"; // 设置背景颜色为深色
this.opacity = 1; // 设置透明度为 1,实现淡入效果
} else {
this.show = false;
this.searchBgc = "rgba(0, 0, 0, 0.1)"; // 设置背景颜色为浅色
this.opacity = 0; // 设置透明度为 0,实现淡出效果
}
} else {
if (this.oldScrollTop == oldValue) {
// console.log("滚动开始");
}
}
}, 20);
},
immediate: true
}
},
// 其他方法...
};
```
阅读全文