DOM外联样式相关操作

DOM外联样式相关操作

DOM在对css样式进行修改的时候,直接使用style会出现无法获取外联样式表样式的情况,这时需要使用CSS 样式声明对象(CSSStyleDeclaration),其中有一个cssText属性,用于设置或返回样式声明文本,cssText 对应的是 HTML 元素的 style 属性。

语法如下:

返回 cssText 属性:

element.style.cssText

设置 cssText 属性:

element.style.cssText = style

设置指定元素的内联样式:

document.getElementById("ex1").style.cssText = "color: blue;";

获取外联样式:

let child1 = document.getElementById("div2");
let style1 = window.getComputedStyle(child1);

详细案例如下:(vue文件)

<template>
  <div class="rainRound" id="div1" style>
    <div class="yudi" id="div2" style="margin-left:120px"></div>
  </div>
</template>

<script>
export default {
  name: "testVue",
  data() {
    return {
      //
    };
  },
  mounted() {
    let el = document.createElement("div");
    let child1 = document.getElementById("div2");
    let style2 = window.getComputedStyle(child1);
    let style1 = child1.style;
    el.style.cssText = style2.cssText;
    let style3 = el.style;
    let leftA = Math.floor(Math.random() * 1660 + 2);
    el.style.marginLeft = leftA + "px";
    let par = document.getElementById("div1");
    par.appendChild(el);

    // for (let i = 0; i < 100; i++) {
    //let par = document.getElementById("div1");
    //for (let i = 0; i < 30; i++) {
    //  let clone1 = child1.cloneNode(true);
    //  let leftA = Math.floor(Math.random() * 1660 + 2);
    //  clone1.style.marginLeft = leftA + "px";
    //  let sec = Math.floor(Math.random() * 10 + 1);
    //  clone1.style.animationDelay = sec + "s";
    //  par.appendChild(clone1);
    //}
    //let el = document.createElement("div");
    //el.style = style1;
    //let classA = document.createAttribute("class");
    //classA.nodeValue = "yudi";
    //el.attributes.setNamedItem(classA);
    //el.style.marginLeft = leftA + "px";
    //par.appendChild(el);
  //},
  //methods: {
    //
  },
};
</script>

<style lang="scss" scoped>
.rainRound {
  position: relative;
  height: 100%;
  background-color: rgb(150, 187, 179);
  .yudi {
    position: relative;
    width: 4px;
    height: 6px;
    background-color: aqua;
    clip-path: ellipse(10% 30% at 50% 50%);
    transform: scale(6);
    animation: roundRain 1s ease-in infinite;
  }
}
@keyframes roundRain {
  0% {
    opacity: 0;
  }
  20% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translate3d(10px, 700px, -10px);
  }
}
</style>
posted @ 2020-09-09 14:27  沐雨辰沨  阅读(162)  评论(0编辑  收藏  举报