javaScript系列---【操作元素样式】

操作元素样式

原则:用过style属性操作的都是元素的行内样式(设置和获取)

操作单个样式

  • 基本语法

    设置 :

    元素.style.样式属性 = 

    获取:

     元素.style.样式属性

    代码如下:

    var box =document.getElementById("box");

    // 设置
    box.style.width = "400px";
    box.style.height = "400px";
    // js中全部遵循驼峰命名法
    box.style.fontSize = "22px";
    box.style.backgroundColor = "blue";

    // 多次设置当前这个属性 后边的覆盖前边的
    box.style.width = "600px";

    // 获取
    // 行内有才能获取到,没有获取到的是空字符串
    console.log(box.style.width);
    console.log(box.style.height);
    console.log(box.style.fontSize);
    console.log(box.style.backgroundColor);

操作样式集合

  • 注意:会把style对应的值整体覆盖了

  • 基本语法:

    设置:

    元素.style.cssText = "行内样式值"
    //cssText ->符合CSS写法

    获取:

    元素.style.cssTex; 
    //将行内style属性对应的值整体获取到 (符合CSS写法)

    代码如下:

    var box = document.getElementById("box");

    // 设置
    // 会把style对应的值整体覆盖了
    box.style.cssText = "200px;height:200px;
    // box.style.cssText = "font-size:60px";
    // box.style.cssText = "200px";

    // 获取
    console.log(box.style.cssText);

     

  •  

原文地址:https://www.cnblogs.com/chenhaiyun/p/14520664.html