JS 操作Dom节点之样式

为了提高用户体验,我们经常会动态修改Dom节点的样式,各种浏览器差异比较大,我们如何应对?不断尝试,不断总结~!

1. style、getComputedStyle、currentStyle

 

内嵌样式:

<!--body -->
<
div style="width: 30px;background-color: #ff6a00;">我就是傻里傻气的,完全素颜!</div>

 

1 //内联样式优先级最高,通过style获取的样式是最准确的 2 var elm = document.getElementById('J-demo'); 3 4 //通常这样获取 5 elm.style.width 6 elm.style.backgroundColor

 

内联样式、外部样式:

<!--css-->

<link ref="stylesheet" href="demo.css">



<style>

    .demo {

        width: 30px;

        background-color: #ff6a00;

    }

</style>





<!--body -->

<div id="J-demo" class="demo">你想那么容易看我素颜?没那么容易...</div>

 

 1 var elm = document.getElementById('J-demo'),

 2     elmStyle;

 3 

 4 elm.style.xxx  //只能获取定义的内联样式

 5 

 6 //如果标签没有定义相关的内联样式,应该这么办:

 7 elmStyle = elm.currentStyle ? elm.currentStyle.getAttribute('background-color') : window.getComputedStyle(elm, null).getPropertyValue('background-color');

 8 

 9 getPropertyValue(name)   //name不要使用驼峰命名的名称

10 getAttribute(name)  //如果考虑该死的IE6, name 必须是驼峰命名的名称

11 

12 //为什么不用下标[name]来获取属性值呢?

13 //浏览器对样式属性解释名称不一样,比如float,有的叫cssFloat,有的叫styleFloat

 

2. screen属性

//显示器可用宽度、高度,不包含任务栏

availWidth、availHeight



//显示器屏幕的宽度、高度

width、height

 

3. 元素视图方法、属性

 1 //让元素滚动到可视区域

 2 scrollIntoView()

 3 

 4 //内容区域的左上角相对于整个元素左上角的位置(包括边框)

 5 clientLeft

 6 clientTop

 7 

 8 //内容区域的高度和宽度,包括padding,不包括边框和滚动条

 9 clientWidth

10 clientHeight

11 

12 //相对于最近的祖先定位元素的偏移值

13 offsetLeft

14 offsetTop

15 

16 //返回最近的且定位的祖先元素

17 offsetParent

18 

19 //offsetParent元素只可能是下面这几种情况:

20 //1. <body>

21 //2. position不是static的元素

22 //3. <table>, <th> 或<td>,但必须要position: static

23 

24 //整个元素的尺寸(包括边框)

25 offsetWidth

26 offsetHeight

27 

28 //元素滚动的像素大小,可读可写

29 scrollLeft

30 scrollTop

31 

32 //整个内容区域的宽高,包括隐藏部分

33 scrollWidth

34 scrollHeight

35 //兼容问题:当外层元素没有设置overflow,但内容超过外层元素宽高时,浏览器获取的值将不准确

36 //解决方法:对外层元素设置overflow属性

 

4. 鼠标位置

1 //鼠标相对于window的偏移

2 event.clientX

3 event.clientY

4 

5 //鼠标相对于显示器屏幕的偏移坐标

6 event.screenX

7 event.screenY

 

.Thingking

学会这些通用的样式处理方法,操作Dom样式,制作出漂亮的页面style,将会更加得心应手。

Reference: http://www.quirksmode.org/dom/w3c_cssom.html

 

你可能感兴趣的:(dom)