1. 获取元素的非行内样式
<!-- 行内样式 -->
<div style="width:100px;height:100px;background:yellow;"></div>
<!-- 内联样式/外链样式 -->
<span class="sp">内联样式/外链样式</span>
//<style> .sp{position: absolute;width: 500px;height: 200px;background-color: green;}</style>
-
IE类:currentStyle
- 语法:元素.currentStyle.要获取的属性
-
非IE:getComputedStyle
- 语法:window.getComputedStyle(元素,null).要获取的属性
-
eg:
//1.获取当前div节点
var div =document.querySeletor('div');
//获取div元素的行内样式
console.log(div.style.width)
//需求获取span的内联样式、外链样式
//1.获取当前span元素的样式
console.log(span.style.width);//无法实现内联样式
//IE 方法:currentStyle
console.log(span.currentStyle.width)
//非IE方法:getComputeStyle
console.log(window.getComputedStyle(span,null).width)
2.获取元素偏移量(元素在页面上的位置)
- offsetLeft、offsetTop->获取的是元素左边的偏移量和上面的偏移量.
注意:
- 没有到位的情况:获取元素边框外侧距离页面内侧的距离.
- 有定位的情况:获取元素边框外侧距离最近的有定位的父元素的边框内侧的距离.
- offsetWidth、offsetHeight->获取的元素的宽高 = 内容的+padding的+border的(不带单位,是number类型,方便参加运算).
//获取div这个元素节点
var div = document.querySelector('div');
//offsetWidth、offsetHeight
console.log("div的宽度是:")
console.log(div.offsetWidth);
console.log("div的高度是:")
console.log(div.offsetHeight);
//offsetLeft、offsetTop
console.log("div上面的偏移量是:")
console.log(div.offsetTop);
console.log("div左面的偏移量是:")
console.log(div.offsetLeft);