我试图创建垂直滚动动画。
我在div中有9个元素,隐藏溢出和高度,你当时只能看到3个。
每隔5秒,我只想添加减去margin-top
的样式并更改orderStep
变量。因此,如果orderStep等于1,那么当我添加margin-top: -190px;
时,我将所有元素边距添加到0,当它添加methods
时,我添加-380px。
我有一个函数,它在created
对象中执行此操作,并在从后端获取记录后在 data() {
return {
articles: [],
errors: [],
step: 1
}
},
methods: {
changeSlide() {
const elements = document.querySelectorAll('.most__popular');
setInterval(() => {
switch (this.step) {
case 1:
for(let val of elements) {
val.style.margin = "10px 0";
}
this.step = 2;
break;
case 2:
for(let val of elements) {
val.style.margin = "-190px 0 0 0";
}
this.step = 3;
break;
case 3:
for(let val of elements) {
val.style.margin = "-380px 0 0 0";
}
this.step = 1;
break;
}
},5000);
}
},
async created() {
try {
const response = await axios.get(`/api/article/getMostPopular.php`, axiosConfig);
this.articles = response.data.records;
this.changeSlide();
} catch (e) {
this.errors.push(e)
}
},
执行它。
不幸的是,它不起作用,我的代码是:
data()
它根本不会改变我元素的风格。在firefox控制台中,我没有任何错误。
我在document.querySelectorAll
中看到的步骤变量的初始值为1(我在编辑中添加了它)。
修改
我已经做了一些调试,我发现v-for
没有给我正确的NodeList,它是空的。这可能是因为我引用了来自异步后端调用(response
来自created()
的{{1}}呈现的元素,但我认为我可以参考它在axios.get
下方,如何解决?
EDIT2
现在正如RoyJ推荐的那样(可能是因为我不应该操纵DOM,因为vue使用其虚拟DOM)在评论部分我通过模板中的:style
指令绑定样式
<div class="most__popular"
v-for="n in articles" :key="n.id"
:style="{margin: sliderMargin}">
所以我设置的margin等于我在函数中改变的sliderMargin变量:
changeSlide() {
setInterval(() => {
switch (this.step) {
case 1:
console.log('step1');
this.sliderMargin = '10px 0 0 0';
this.step = 2;
break;
case 2:
console.log('step2');
this.sliderMargin = '-190px 0 0 0';
this.step = 3;
break;
case 3:
console.log('step3');
this.sliderMargin = '-190px 0 0 0';
this.step = 1;
break;
}
},5000);
}
但它没有按照我想要的方式工作,因为它为每个元素增加了余量,因此结果它不会滚动但它已经消失了。所以我要做的是:
问题是,如果:style
等于2或6,如果this.step
等于3,则问题是如何仅对前三个调整this.step
,如果this.step
等于1则如何调整为无?
答案 0 :(得分:1)
在setInterval
中,您不会测试this.step
,您只是要更新其值。它使用模运算来循环遍历0,1,2的值。
您将根据其索引(0 - 5)和this.step
的值计算每个文章的边距。因此sliderMargin
是一个数组,其中articles
的每个元素都有一个元素。在v-for
中,使用sliderMargin
中与article
对应的元素。
thresholds
表示给定步骤的文章有多少10px边距与-190px边距。
new Vue({
el: '#app',
data: {
articles: [1,2,3,4,5,6],
step: 0
},
computed: {
sliderMargin() {
const thresholds = [0, 3, 6];
return this.articles.map((_, i) =>
`${(i < thresholds[this.step]) ? '10px' : '-190px'} 0 0 0`
);
}
},
mounted() {
setInterval(() => {
this.step = (this.step + 1) % 3;
}, 5000);
}
});
&#13;
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<div class="most__popular" v-for="n, i in articles" :key="n.id" :style="{margin: sliderMargin[i]}">
{{n}}
</div>
</div>
&#13;