JavaScript(二)

属性、样式操作

改变元素样式的方式:外部样式表、内部样式表、行内样式。

获取元素的显示样式

获取节点的方式:

通过id获取:document.getElementById()
通过选择器来获取:document.querySelector(),document.querySelectorAll()
通过class名字获取:document.getElementsByClassName()
通过标签名获取:document.getElementsByTagName()
通过name获取:document.getElementsByName()

用classList来操作类名

添加类名: .classList.add()  
移除类名: .classList.remove()
切换类名(有则移除,没有则添加): .classList.toggle()
let oWrap = document.getElementById("wrap");

    //不标准的写法
    // oWrap.style = "width: 300px";

    //style 这个合法的标签属性很特殊
    console.log( oWrap.style );

    oWrap.style.width = "300px";
    oWrap.style.height = "200px";
    oWrap.style.backgroundColor = "red";


//样式操作
let oWrap = document.getElementById("wrap");

    oWrap.onclick = function(){
      // oWrap.style.width = "500px";

      //在事件函数里面,可以用 this来代替oWrap
      this.style.width = "500px";
    };
//变相操作样式
let oWrap = document.getElementById("wrap");

    oWrap.onclick = function(){
      //添加名字,点击时,更换名字生成样式
      this.className = "fly";
    };
 
posted @ 2020-12-31 17:09  小衣  阅读(126)  评论(0编辑  收藏  举报