我正在尝试用Vue.js在图像上创建一个悬停效果。我写了以下代码,但现在当我将鼠标悬停在其中一个图像上时,文本显示在所有图像上。如何解决此问题?我只希望显示属于我悬停在其上的图像的文本。提前感谢您的帮助。
Vue模板:
<template>
<div class="row partner-body-row">
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = true"
@mouseleave="showText = false"
>
<img
class="hover-img"
src="img/img-1"
alt="img-1"
/>
<span v-if="showText">Text 1</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = true"
@mouseleave="showText = false"
>
<img
class="hover-img"
src="img/img-2"
alt="img-2"
/>
<span v-if="showText">Text 2</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = true"
@mouseleave="showText = false"
>
<img
class="hover-img"
src="img/img-3"
alt="img-3"
/>
<span v-if="showText">Text 3</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = true"
@mouseleave="showText = false">
<img
class="hover-img"
src="img/img-4"
alt="img-4"
/>
<span v-if="showText">Text 4</span>
</div>
</div>
</div>
</template>脚本:
export default {
data: () => {
return {
showText: false,
};
},
};发布于 2021-09-25 20:18:34
所有条件都绑定到同一个变量,让该变量保存每个图像的编号,而不仅仅是true/false。
理想情况下,这应该使用:hover在CSS中完成。
<template>
<div class="row partner-body-row">
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = 1"
@mouseleave="showText = 0"
>
<img
class="hover-img"
src="img/img-1"
alt="img-1"
/>
<span v-if="showText === 1">Text 1</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = 2"
@mouseleave="showText = 0"
>
<img
class="hover-img"
src="img/img-2"
alt="img-2"
/>
<span v-if="showText === 2">Text 2</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = 3"
@mouseleave="showText = 0"
>
<img
class="hover-img"
src="img/img-3"
alt="img-3"
/>
<span v-if="showText === 3">Text 3</span>
</div>
</div>
<div class="col">
<div
class="img-wrapper"
@mouseover="showText = 4"
@mouseleave="showText = 0">
<img
class="hover-img"
src="img/img-4"
alt="img-4"
/>
<span v-if="showText === 4">Text 4</span>
</div>
</div>
</div>
</template>
export default {
data: () => {
return {
showText: 0,
};
},
};发布于 2021-09-25 20:51:49
您可以使用工具提示为每个图像创建一个组件,如下所示:
Vue.config.productionTip = false;
const Img = {
name: 'Img',
props: ['src'],
data() {
return { showText: false }
},
template: '<div><img @mouseover="showText = true" @mouseleave="showText = false":src="src" /><span v-if="showText">Tooltip</span></div>',
};
const App = new Vue({
el: '#root',
components: { Img },
template: '<div><Img src="https://via.placeholder.com/150"/><Img src="https://via.placeholder.com/150"/></div>',
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root"/>
发布于 2021-09-26 01:37:33
如果它只是为了显示悬停时的文本。你不需要使用v-model。在这种情况下,您将使用css。
您可以从<span>中删除所有v-if's并添加此css
.image-container span {
display: 'none';
}
.image-container:hover span {
display: 'block';
}https://stackoverflow.com/questions/69329671
复制相似问题