JavaScript 原生控制元素添加删除

参考:

https://blog.csdn.net/leijie0322/article/details/80664554

https://www.cnblogs.com/jpfss/p/9106209.html

需求是要求在图片上添加一个动画效果,可以位置、颜色、大小等参数,

1、在原有的图片上增加一个动画层、

2、动态更换动画参数

3、删除之前加载的动画,更新动画。

      <div
        v-else
        @mousedown="move"
        @touchstart="phonetouchstart"
        @touchmove="phonetouchmove"
        @touchend="phonetouchend"
        align="justify"
        class="img3dmodels"
      >
        <img  />
        <div ></div> //这里就是动画层了

      </div>

添加div

    setanimationparameter(op, parameter) {
      // 创建动画var divs = document.createElement("div") // 创建div
      var cass = document.createAttribute("class"); //创建class定义
      cass.value = "animation"; //添加class
      divs.setAttributeNode(cass) //div绑定class
      var style = document.createAttribute("style"); // 创建style
      divs.setAttributeNode(style); // 绑定style

      divs.style.width = parameter.w;
      divs.style.height = parameter.h;
      divs.style.left = parameter.x;
      divs.style.top = parameter.y;
      divs.style.backgroundColor = parameter.color;
      op.appendChild(divs) // 添加到动画层

    },

清空div

    removeanimation(){
      //清空动画、清空动画层内所有的元素
      let op = document.getElementById("animation_div");
      op.innerHTML ='' 
    },

执行代码

setanimation(parameter,imgIndex) {
      let op = document.getElementById("animation_div");
      this.removeanimation()
      // 楼栋名称、底图、位置、大小、形状、显示隐藏
      // parameter : 动画参数
      // imgIndex : 展示底图名称
      // console.log(parameter)
      this.img_url = `${this.imgpwd}${this.filename}${this.prefix}${imgIndex}.png`;
      
      if(parameter){
          if (parameter.length){
            for (let index = 0; index < parameter.length; index++) {
              const element = parameter[index];
              this.setanimationparameter(op,element);
            }
          }else{
            this.setanimationparameter(op,parameter);
          }
        console.log("更换动画");
      }else{
        console.log('动画参数为空')
      }
      
    },