在Vue实例中,我有一个名为“block”的数组,其中包含4个值。我使用v-for将此数组呈现到DOM中:
这将创建一个带有4个 span 的 div,每个 span 都有一个类名为 "index--0"、"index--1" 等。
点击时,Array 的值会改变顺序:
也许有一种仅使用CSS的解决方案,不需要DOM操作。
<div class="block" @click="shuffleArray()">
<div v-for="(number, index) in block">
<span :class="[`index--${index}`]">{{ number }}</span>
</div>
</div>
这将创建一个带有4个 span 的 div,每个 span 都有一个类名为 "index--0"、"index--1" 等。
点击时,Array 的值会改变顺序:
shuffleArray: function() {
const shifted = this.block.shift();
this.block.push( shifted );
}
虽然值会发生变化,但它们不会在实际的DOM中移动,那么我如何实现当单击时,这些span实际上可以在DOM中改变位置呢?每个span都有一个应用于它的样式,因此我希望有一个视觉表示值确实改变了顺序:
span.index--0 {
background-color: tomato;
}
span.index--1 {
background-color: khaki;
}
span.index--2 {
background-color:lavenderblush;
}
span.index--3 {
background-color: lightcoral;
}
也许有一种仅使用CSS的解决方案,不需要DOM操作。