在js中获取在css中设置的background-image值
1. html部分
<div class="bg-color-two" id="bg_color_two" onclick="setBg(this)"></div> <div class="bg-color-three" id="bg_color_three" onclick="setBg(this)"></div>
2. css部分
.bg-color-two { width: 40px; height:40px; background-image:url(811915c596d17e09d4f85bd7e80ccee7.jpg); background-size:40px 40px; } .bg-color-three { width: 40px; height:40px; background- image:url(675aa3366a8cda46febf0053c82e4f27.jpeg); background-size:40px 40px; }
3. js部分
function setBg(control) { //google用getComputedStyle(object, attr)方法获取style属性 var bgImage = getComputedStyle(document.getElementById(control.id), "style").backgroundImage; console.log(bgImage); //bgImage = "url(file:///C:/Users/Gladys/Desktop/811915c596d17e09d4f85bd7e80ccee7.jpg) }
注意:fire和google chrome都可以用getComputedStyle(object, attr)方法获取style属性,而IE浏览器用getStyle(object, attr)获取style里面的属性