簡體   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