js获取、设置元素属性值

文章目录

      • setAttribute
      • getAttribute
      • getComputedStyle
      • currentStyle
      • `元素.style.属性名`

网页css和样式结构

#box{width:100px;height:100px;
}
<div id="box" style="background:red;">div>

setAttribute

  • 元素.setAttribute('属性名',属性值)
  • 设置元素的行间属性,如果原来有这个行间属性会覆盖原来的行间属性
  • 可以通过该方法给元素新增自定义行间属性
var oBox = document.getElementById("box");
oBox.setAttribute("width","200px");//给oBox对象新增行间属性width="200px",不能覆盖css样式中的width属性值
oBox.setAttribute("class","myDiv");//给oBox对象新增行间属性class="myDiv"

getAttribute

  • 元素.getAttribute('属性名')
  • 获取元素的行间属性对应的属性值,不能获取css样式对应的属性值
  • 如果获取的属性不存在返回null
var oBox = document.getElementById("box");
console.log(oBox.getAttribute("width"));//null

getComputedStyle

  • 获取经过浏览器计算后的属性
  • 获取的结果是带单位的字符串
  • getComputedStyle是window对象的一个属性,属性值是一个方法。这个方法的返回结果是一个对象
  • 该方法具有兼容性问题,在ie8及以下版本不存在该属性
var oBox = document.getElementById("box");
console.log(getComputedStyle(oBox).width);//"100px"

currentStyle

  • 在ie8及以下版本没有getComputedStyle属性,但是存在currentStyle属性。在ie9及以上版本均存在getComputedStyle、currentStyle属性。该属性名在谷歌浏览器不存在
  • 该属性时元素对象上的属性,对应的属性值是一个对象

元素.style.属性名

  • 获取或设置元素的内置的行间样式属性
  • 返回的结果是带单位的字符串
  • 可以设置元素的内置行间样式属性,属性值是带单位的字符串
var oBox = document.getElementById("box");
oBox.style.width = "300px";//将盒子的宽度设置为300px


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部