当前位置:首页 > Web开发 > 正文

attributeValue) 指定属性设置或更改为指定值 element.removeAttribute(attri

2024-03-31 Web开发

标签:

操纵属性和类 一、属性节点操纵   文本节点内容的获取和改削:

    语法:elementNode.attributeName ( 元素节点.属性名)
          也可以使用“[ ]”  ( 元素节点[属性名])


  注意:一般我们操纵属性节点时是不需要获取属性节点的,,而是直接通过元素节点获取(/改削)属性节点的值。

          特另外,有些属性名称与js关键字或者保存字斗嘴了,只能用此外的名字:
       class属性:要写成className(class是关键字)。
       label标签的for属性:写成htmlFor。


  通过要领操纵属性节点:


    element.getAttribute(attributeName)            返回元素节点的指定属性值


    element.setAttribute(attributeName, attributeValue)    指定属性设置或变动为指定值


    element.removeAttribute(attributeName)        从元素中移除指定属性


    ement.hasAttribute(attributeName)            如果元素拥有指定属性,则返回true

二、自界说属性

  自界说属性:给html标签写一个本身界说的属性。

  虽然给一个东西添加属性很简单,但是在dom中,给元素节点添加自界说的属性节点,html5中要求自界说属性节点应该为‘data-’开头,

  好比自界说属性abc,应该写成:       

      data-abc
  这样,要使用时就通过dataset属性即可操纵了:


  例如:a标签有自界说属性‘abc’

<a href="" data-abc=‘123‘></a> <script> let aEle = document.querySelector(‘a’); console.log(aEle.dataset.abc);//123 </script>

注意:attribute相关要领可以操纵任意属性,包孕自界说属性(对自界说属性使用时必需加‘data-’)


三、html5中class属性的新操纵


  使用classList获取一个元素节点上所有的class值:

<body> <p>Lorem ipsum dolor sit amet.</p> <script> let test1 = document.getElementById("test1"); console.log(test1.classList); // DOMTokenList(2) ["abc", "qwe", value: "abc qwe"] console.log(test1.classList[0]); // abc console.log(test1.classList[1]); // qwe </script> </body>

  classList相关要领: 


      element.classList.add(className)         添加一个指命名字的class值


      element.classList.remove(className)        删除一个指命名字的class值


      element.classList.contains(className)       判断一个指命名字的class值


      element.classList.toggle(className)          切换一个指命名字的class值,有则删除,无则添加

操纵样式   所有的样式都是字符串。 一、行内样式   单个样式:

    element.style.styleName;


    例子:divEle.style.width=‘200px’;
          element.style.[styleName];
    例子:divEle.style[‘width‘]=‘200px’;


注意:样式名称中的‘-’去失,换成驼峰定名。

   学习html,css时要求少用行内样式,就是为了留给js用的,所以,js中操纵css,大都情况下是使用该方法。

  多个样式:

    element.style.cssText    直接获取(/改削)行内样式的整个字符串值


    例子: box.style.cssText = "height: 100px; background-color: red;";

注:根基都适用此种方法。


二、样式表样式

    样式表(包孕内联和外联):


      document.styleSheets[0].rules[0].style.backgroundColor = "blue";


        styleSheets:样式表数组(一个style标签为一个样式表);
        rules:所有法则数组(一个“{}”为一条法则);
        所以含义是:第0个样式表中第0条法则中的backgroundColor改削为“blue”。

注:根基不用这种方法。


三、最终样式

    由于兼容性问题,最终样式有两种写法:


      低版本ie中,用属性currentStyle:
         element.currentStyle.styleName ;


      火狐和chrome中(现代浏览器),用要领getComputedStyle:
         getComputedStyle (Element) .styleName ;


注意:按照需要会使用,但最终样式都是计算出来的样式,为只读的,不成改削。


    兼容性封装:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/33076.html