zoukankan      html  css  js  c++  java
  • 使用datasest属性改变样式

    使用datasest属性改变样式

    传统做法

    对于html中的标签我们可以自定义标签中的属性,例如给input加一个aaa属性

    <input type="text"  aaa="bbb">
    

    接下来获取input的属性并在控制台中输出,即:

    let intype = document.querySelector("input");
        console.log("intype.type:"+intype.type);
        console.log("intype.aaa:"+intype.aaa);
    

    在控制台中可以看到

    也就是说无法通过 元素.属性名的方式 直接获取属性aaa的值

    这时候只能通过 元素.getAttribute('属性名') 来获取其属性值,代码入下:

    console.log("intype.getAttribute('aaa'):"+intype.getAttribute("aaa"));
    

    结果如下

    而要改变该元素属性的方法则是 元素.setAttribute('属性名','属性值') 代码如下

     intype.setAttribute("aaa","ddd");
    

    此时在检查元素可以看到

    dataset

    而通过data-属性名 这种方法可以 自定义属性名并通过 data.属性名获取属性值

    举例:

    ​ 通过按钮改变背景颜色

    <body>
        <button data-acolor="red">红</button>
        <button data-acolor="yellowgreen">绿</button>
        <button data-acolor="skyblue">蓝</button>
    </body>
    <script>
    
        let btns = document.getElementsByTagName("button");
        for (let i = 0; i < btns.length; i++) {
            btns[i].onclick = function () {
                document.body.style.backgroundColor = this.dataset.acolor;
            }
        }
    </script>
    

    如上通过给每个button指定一个data-acolor 属性,则可以在button的点击事件中使用this进行指定,

    从而实现点击不同的按钮更换不同的背景色

    补充:

    ​ 点击按钮切换背景色除了上述方式也可通过数组进行赋值,具体代码如下(布局可不用改变):

    let btns = document.getElementsByTagName("button");
        let color_list = ["red","yellowgreen","skyblue"]
        for(let i = 0;i < btns.length;i++){
            //为btn添加一个属性index
            btns[i].index = i;
            btns[i].onclick = function(){
                document.body.style.backgroundColor = color_list[this.index];
            }
        }
    
  • 相关阅读:
    远程诊断DoIP
    基于linux内核包过滤技术的应用网关
    Boost内存池使用与测试
    C++ 编程规范
    大象——Thinking in UML
    C++ 创建类时常考虑的问题
    SLIP—串行线路上传输数据报的非标准协议
    神秘的程序员——编程的乐趣
    Bad Smell (代码的坏味道)
    模式与软件架构——软件架构的非功能特征
  • 原文地址:https://www.cnblogs.com/axu1997/p/11844331.html
Copyright © 2011-2022 走看看