天天看点

javascript基础2

自定义属性

<div id="box" stuId = "1">张三</div><a href="#" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" >删除</a>
    <script>
    var box = document.getElementById('box');
    console.log(box.stuId);  //当访问对象中不存在的属性,返回undefined
    </script>
           

在chrome中不能使用上面方式获取标签的自定义属性。

  • getAttribute()获取标签行内属性
  • setArrribute()设置标签行内属性
  • removeAttribute()移除标签行内属性
  • 与element.属性的区别:上述三个方法用于获取任意的行内属性。
<div id="box" stuId = "1">张三</div><a href="#" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" >删除</a>
<script>
//获取标签自定义属性
    console.log(box.getAttribute('stuId'));
    //设置标签的自定义属性
    box.setAttribute('test','hello');
    //设置标签本身具有的属性
    box.setAttribute('class','bg');
    //移除属性
    box.removeAttribute('test');
    box.removeAttribute('class');
    // 不可以设置标签的自定义属性,但是box对象本身具有了abc属性
    box.abc = 'hello';
    console.log(box.abc);
           

 样式操作和类名操作

①使用style方式设置的样式在标签行内(注:通过样式属性设置宽高、位置的属性类型是字符串,需加上px)。

this.style获取的仅仅是标签的style中设置的样式,如果标签没有设置style、属性,此时获取的都是空字符。

//this.style 获取的仅仅是标签的style中设置的样式属性,如果标签没有设置style属性,此时获取的都是空字符串
            console.log(this.style);
           

修改标签 的className属性相当于直接修改标签的类名

【注】如果设置的样式属性比较多时,推荐使用class,反之推荐使用style。

var box = document.getElementById('box');
        //样式操作
        //1 设置类样式
        box.className='box';
        //2 设置行内样式style
        console.dir(box);
        box.style.width = '200px';
        box.style.height = '200px';
        box.style.backgroundColor = 'red';
        //cssText 获取标签的style属性中的字符串
        console.log(box.style.cssText);
           

 【注意】

类名操作中,元素.className的方式可能会覆盖原有的类选择器。使用时不能替换掉原有的类选择器。

QRShow.className="show";    //会覆盖原有的类选择器,可通过下面方法解决 
  QRShow.className="QRShow show"     //方法一
  QRShow.className = QRShow.className.replace('hide','show');   //方法二
           

 【扩展】

选择器的优先级

为同一个元素设置多个样式时,此时哪个样式生效由选择器的优先级确定

· 内联样式 id选择器 类和伪类选择器 元素选择器 统配选择器 继承的样式
优先级 1000 100 10 1
  •  当一个选择器中含有多个选择器时,需要将所有的选择器的优先级进行相加,然后再进行比较,优先级高的优先显示,选择器的计算不会超过其最大的数量级(10个id选择器的优先级不能达到1000)
  • 分组选择器(并集选择器)的优先级单独计算,不会相加。
  • 样式后面加!important,该样式获取最高优先级,内联样式不能加!important属性。
  • 样式相同的谁在下面执行谁(样式的覆盖)。

节点操作

元素节点和属性节点

<div id="box"></div>
    <script>
        //元素节点
        var box = document.getElementById('box');
        //nodeName   标签的名称
        //nodeType     节点的类型  1  元素节点
        //nodeValue     当是元素节点的时候nodeValue始终是null
        console.dir(box);

        //属性节点 ---节点就是对象
        //获取属性节点
        //nodeName   属性的名称
        //nodeType     节点的类型  2  属性节点
        //nodeValue    属性的值
        var arr = box.getAttributeNode('id');
        console.dir(arr);
    </script>
           

nodeType节点的类型

  • 元素节点
  • 属性节点
  • 文本节点

nodeName :节点的名称

nodeValue:节点值(元素节点的nodeValue始终是null)