Vue.js - 如何在滚动时更改图像 src?
Vue.js - How to change image src on scroll?
如果用户向下滚动,我想更改导航栏中的徽标 (img src)。我该怎么做?我只找到了可以更改 css.
的解决方案
<div class="logo">
<img src="@/assets/img/Logo1.png" />
</div>
首先,你需要监听滚动,然后当用户滚动时你检查当前滚动的值,如果这个值足够你改变你设置的图像到你需要的状态更改默认图像。
要允许更改是动态的,您需要在图像的 src 属性中放置一个条件渲染,其中包含您要交换的图像。
handleScroll 的第二个条件是,如果用户滚动的次数少于 100 次,并且不是默认图像,则重新放置默认图像
这是实现它的代码
<template>
<div id="app" style="height: 1800px">
<img
style="position: fixed"
alt="Vue logo"
:src="
isDefaultImage
? 'https://thumbs.dreamstime.com/b/t%C3%AAte-et-visage-de-portrait-mouette-adulte-harengs-semblant-droits-125872008.jpg'
: 'https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg'
"
width="25%"
/>
<HelloWorld msg="Hello Vue in CodeSandbox!" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
isDefaultImage: true,
};
},
created() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
console.log(window.scrollY);
if (window.scrollY > 100) {
return (this.isDefaultImage = false);
}
if (window.scrollY <= 100) {
if (!this.defaultImage) {
return (this.isDefaultImage = true);
}
}
},
},
};
</script>
Link 到代码沙箱:https://codesandbox.io/s/nameless-brook-q5l3g?file=/src/App.vue
如果用户向下滚动,我想更改导航栏中的徽标 (img src)。我该怎么做?我只找到了可以更改 css.
的解决方案<div class="logo">
<img src="@/assets/img/Logo1.png" />
</div>
首先,你需要监听滚动,然后当用户滚动时你检查当前滚动的值,如果这个值足够你改变你设置的图像到你需要的状态更改默认图像。
要允许更改是动态的,您需要在图像的 src 属性中放置一个条件渲染,其中包含您要交换的图像。
handleScroll 的第二个条件是,如果用户滚动的次数少于 100 次,并且不是默认图像,则重新放置默认图像
这是实现它的代码
<template>
<div id="app" style="height: 1800px">
<img
style="position: fixed"
alt="Vue logo"
:src="
isDefaultImage
? 'https://thumbs.dreamstime.com/b/t%C3%AAte-et-visage-de-portrait-mouette-adulte-harengs-semblant-droits-125872008.jpg'
: 'https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg'
"
width="25%"
/>
<HelloWorld msg="Hello Vue in CodeSandbox!" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
isDefaultImage: true,
};
},
created() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
console.log(window.scrollY);
if (window.scrollY > 100) {
return (this.isDefaultImage = false);
}
if (window.scrollY <= 100) {
if (!this.defaultImage) {
return (this.isDefaultImage = true);
}
}
},
},
};
</script>
Link 到代码沙箱:https://codesandbox.io/s/nameless-brook-q5l3g?file=/src/App.vue