Vue.js - 如何在滚动时更改图像 src? [英] Vue.js - How to change image src on scroll?
问题描述
如果用户向下滚动,我想更改导航栏中的徽标 (img src).我该怎么做?我只找到了可以更改 css 的解决方案.
<img src="@/assets/img/Logo1.png";/>
首先你需要监听滚动,然后当用户滚动时你检查当前滚动的值,如果值足够你更改您在需要更改默认图像的状态下设置的图像.
要允许动态更改,您需要在图像的 src 属性中放置一个条件渲染,其中包含要交换的图像.
handleScroll 的第二个条件,如果用户滚动小于 100 则重新放置默认图片,并且仅当它不是默认图片时
这是实现它的代码
<div id="app";样式=高度:1800 像素">模板><脚本>从./components/HelloWorld"导入HelloWorld;导出默认{名称:应用程序",组件: {你好,世界,},数据() {返回 {isDefaultImage: 真,};},创建(){window.addEventListener(scroll", this.handleScroll);},销毁(){window.removeEventListener(scroll", this.handleScroll);},方法: {句柄滚动(事件){//滚动窗口时要执行的任何代码控制台日志(window.scrollY);如果(window.scrollY > 100){返回(this.isDefaultImage = false);}如果(window.scrollY <= 100){如果(!this.defaultImage){返回(this.isDefaultImage = true);}}},},};
代码沙箱链接:https://Codesandbox.io/s/nameless-brook-q5l3g?file=/src/App.vue
I would like to change the logo (img src) in the navbar if user scrolls down. How can I do it? I found only solutions where I can change the css.
<div class="logo">
<img src="@/assets/img/Logo1.png" />
</div>
First of all, you need to listen to the scroll, then when the user scroll you check the value of the current scroll, if the value is enough for you to change the image you set in the state that you need to change the default image.
To allow the change to be dynamic you need to put a conditionnal render in your src attribute of the image with the images you want to swap.
The second condition on the handleScroll, is to re-put the default image if the user has scrolled less than 100, and only if it was not the default image
Here is the code to achieve it
<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 to the code sandbox : https://codesandbox.io/s/nameless-brook-q5l3g?file=/src/App.vue
这篇关于Vue.js - 如何在滚动时更改图像 src?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!