繁体   English   中英

图片动画不起作用! Vue.js

[英]animation of picture doesn't work! Vue.js

问题是当我使用这个顶部的设置间隔时${this.imgTop++}px

const vue = require("@/assets/images/vue.png");
const bootstrap = require("@/assets/images/bootstrap.png");
const bulma = require("@/assets/images/bulma.png");

export default {
  name: "randImg",
  data() {
    return {
      images: [
        vue,
        bootstrap,
        bulma
      ],
      addedImage: [],
      imgTop: -100,
      imgLeft: -100,
      imgHeight: 64,
      imgWidth: 64,
      changeInterval: 750,
      selectedImage: ''
    }
  },
  created() {
    const randomImg = func => setInterval(func, this.changeInterval);
    randomImg(this.randomImage);
    randomImg(this.addImage);
    randomImg(this.randomPosition);
    setInterval(this.moveImage,50);
  },
  methods: {
    randomImage() {
      const idx = Math.floor(Math.random() * this.images.length);
      this.selectedImage = this.images[idx];
    },
    randomPosition() {
      const randomPos = twoSizes => Math.round(Math.random() * twoSizes);
      this.imgTop = randomPos(window.innerHeight - this.imgHeight);
      this.imgLeft = randomPos(window.innerWidth - this.imgWidth);
    },
    moveRandomImage() {
      const randomImg = func => setInterval(func, this.changeInterval);
      randomImg(this.moveImage);
      this.randomImage();
    },
    addImage() {
      this.addedImage.push({
        style: {
          top: `${this.imgTop}px`,
          left: `${this.imgLeft}px`,
          height: `${this.imgHeight}px`,
          width: `${this.imgWidth}px`
        },
        src: this.selectedImage
      });
    },
    moveImage() {
      this.addedImage.style = {
        style: {
          top: `${this.imgTop++}px`
        }
      }
    }
  }
}

不明白为什么,但这个动画不起作用,基本上我会解释它是如何工作的:每一秒我都在添加新图像与来自addedImage的新位置:[]我希望每张图片都下降(顶部++)

另外这是一个模板:

<div class="randImg">
    <img class="image" :style="image.style"
         :src="image.src"
         v-for="image in addedImage">
</div>

我猜你可以通过在addedImage数组上添加一个观察器来实现你想要的,就像每次添加一个新的图像元素一样,你改变它的style.top

但是你不应该使用嵌套的setIntervals。 我和你分享这个答案,解释原因。


我认为更简单,更轻松的解决方案是使用css,比如创建一个@keyframe转换规则:

.drop {
  animation: dropDown 1.5s ease-in forwards;
}

@for $i from 1 to 10 {
  .drop:nth-child(#{$i}) {
    animation-delay: $i * 1.5s;
    animation-duration: -1.5s;
  }
}

@keyframes dropDown {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(600px);
    opacity: 0;
  }
}

这是一个实例

this.addedImage是一个图像数组,而不是图像。 因此,当您执行this.addedImage.style ,可以向数组添加style属性,但不向数组中的图像添加style属性。

更改moveImage:

moveImage() {
  this.addedImage.forEach(image => {
    image.style.top = image.style.top + 1
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM