js 获取元素 background 各种属性值
平时很少用到 js background 属性,今天因项目需求,遭遇了 background 属性,查了文档,兼容性又是一大坑,整理之后,码了个方法,方便 js 获取元素 background 各种属性值。
一、首先是 backgound 属性,只有 chrome 和 safari, 返回了 background 的全部属性值,连 firefox 都返回空啊!
二、backgroundColor 属性: chrome/safari/firfox 返回了 rgb 格式的颜色值,ie 均是十六进制加 #的颜色值。
三、backgroundAttachment、backgroundRepeat 各个浏览器返回值终于都是统一的了。
四、backgroundImage 属性,返回背景图片的绝对路径,不同的是:除了 chrome/safari 下 url 值是不带引号的,其它浏览器均带双引号。
五、最蛋疼的就是 backgroundPosiiton、backgroundPosiitonY 属性了
A、如果有内联样式通过 elem.style.backgroundPosition 可以取得 backgroundPositionX 和 backgroundPositionY 两个值。
B、但是如果没有内联样式通过计算样式 getComputedStyle(elem,null).backgroundPosition 得到的总是返回 IE 下的 backgroundPositionX 的值,我还没有找到通过 getComputedStyle(elem,null)方法得到 backgroundPositionY 的值得方法,等到找到了再添上来。
具体区别如下:
1.IE6/7/8:识别 backgroundPositionX/Y , 但是不识别 backgroundPosition,ie9+ 两者都识别,但 css 如:background-postion:center, 只指定一个值,ie9+,background 就返回一个值,其它浏览器都会返回两个值。
2.FireFox 和 opera:不识别 backgroundPositionX/Y, 但是识别 backgroundPosition。
3.Safari 和 Chrome:识别 backgroundPositionX/Y 及 backgroundPosition。
下面就来准备填坑吧!代码先贴上:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64function getBackground(ele) {
var background = {
pos: {
x: "",
y: ""
},
image: getStyle(ele, "backgroundImage").replace(/^url\("?|"?\)$/gi, ""),
repeat: getStyle(ele, "backgroundRepeat"),
color: getStyle(ele, "backgroundColor"),
attachment: getStyle(ele, "backgroundAttachment")
}
if (ele.currentStyle) {
background.pos.x = ele.currentStyle.backgroundPositionX;
background.pos.y = ele.currentStyle.backgroundPositionY;
} else {
var pos_arr = window.getComputedStyle(ele, null).backgroundPosition.split(" ");
background.pos.x = window.getComputedStyle(ele, null).backgroundPositionX;
background.pos.y = window.getComputedStyle(ele, null).backgroundPositionY;
background.pos.x = background.pos.x ? background.pos.x: pos_arr[0];
background.pos.y = background.pos.y ? background.pos.y: pos_arr[1];
}
function formatNumber(value) {
var value_num = "";
switch (value) {
case "left":
case "top":
case "0%":
value_num = "0%";
break;
case "right":
case "bottom":
case "100%":
value_num = "100%";
break;
case "center":
case "50%":
value_num = "50%";
break;
default:
value_num = value;
break;
}
return value_num;
}
background.pos.x = formatNumber(background.pos.x);
background.pos.y = formatNumber(background.pos.y);
return background;
}
getStyle 是平时常用的获取元素计算后的 css 属性兼容性方法,这里就不再赘述了。
getBackground()返回一个对象,formatNumber()方法是格式化 left,top,center,right,bottom 这些英文值,返回来 0%,50%,100%,这样格式的数值。
本文地址 https://shaoshilei.com/2014-05/js-obtain-various-background-element-attribute-value.html