vue中使用js根据参数动态设置@keyframes,实现多个时钟不同角度的旋转

效果图:
在这里插入图片描述
核心html代码:

//时钟【实际项目中为探测器,这里用时钟代替】是通过v-for循环出来的
<div class="chart" v-for="(item,index) in currentDetectors" :key="index">
        <div class="electChart">
          <div class="detector">
          //为每一个时钟均添加一个pointer类,设置初始的样式,包括初始位置所在的旋转角度
          //通过v-blind绑定一个style属性,声明每个时钟分别应用的关键帧keyframes动画的名称
            <div
              class="pointer" 
              v-bind:style="{
              animation: 'pointermove'+(index+1)+' 3s forwards',
            }"
            ></div>
          </div>
        </div>
      </div>
    </div>

样式:

.detector {
          width: 427px;
          height: 427px;
          background: url('../../../assets/warning/detectorBg.png') no-repeat;
          background-size: contain;
          align-items: center;
          display: flex;
          .pointer {
            width: 189px;
            height: 34px;
            background: url('../../../assets/warning/pointer.png') no-repeat;
            background-size: contain;
            margin-left: 40px;
            transform-origin: 94% center;
            transform: rotate(301deg);
            animation-iteration-count: 1;
          }
        }

核心:

接下来做的就是根据具体的数据动态的设置keyframes:

  methods: {
    // 模拟该公司的第一页视频监控
    getData() {
      this.getDefaluVideos();
      this.setPointer();
    },
    getDefaluVideos() {
      this.currentDetectors = this.currentDetectors.map((item, index) => ({
        companyId: this.companyId,
        page: 1,
        video: index + 1,
        pointerEnd: 100 + (index + 1) * 30
      }));
    },
    //此方法需要在组件被渲染完之前调用
 	setPointer() {
 	  //循环遍历数组,根据每一个时钟的数据为页面添加不同的keyframes
      this.currentDetectors.forEach((element, index) => {
        let style = document.createElement('style');
        style.setAttribute('type', 'text/css');
        document.head.appendChild(style);
        let sheet = style.sheet;
        //根据每一个时钟的数据为页面添加不同的keyframes
        sheet.insertRule(
          `@keyframes pointermove` +(index + 1) +`{
  			from {
			    transform: rotate(300deg);
  			}
 			 to {
 			 //注意:动态的计算需要先计算再赋值,不然浏览器会直接当字符串来解析
   				 transform: rotate(` +(300 + element.pointerEnd) +`deg);}
			}`,0
        );
      });
	},
   computed: {
    ...mapGetters(['departmentId', 'companyId']),
    totalPages: function() {
      return Math.ceil(this.totalVideos / 6);
    }
  },
  watch: {
    departmentId: {
      handler: 'getData',
      immediate: true
    },
    companyId: {
      handler: 'getData',
      immediate: true
    }
  },

完工!

发布了21 篇原创文章 · 获赞 0 · 访问量 388

猜你喜欢

转载自blog.csdn.net/qq_41800649/article/details/103301112
今日推荐