日期:2014-05-16  浏览次数:20438 次

js怎么获取背景图片呢?用这个返回的是空,不知道是怎么回事
console.log(document.getElementById("mainnav").style)

document.getElementById("id").style.backgroundImage
background获取

------解决方案--------------------
写在样式表里的样式是没办法直接用style来获取的,,

具体的可以自己百度一下currentStyle跟getComputedStyle。
------解决方案--------------------
通过dom的stlye属性或者jquery的$().css(background)

------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{
width:400px;
height:400px;
background-image:url(1.jpg);
background-repeat:no-repeat;
background-color:#933;
background-position:center;
}
</style>
<script type="text/javascript">
function init(){
var a=document.getElementById("test");
var style="";
if(document.defaultView&&document.defaultView.getComputedStyle){
style=document.defaultView.getComputedStyle(a);
}else{
style=a.currentStyle;
}
alert(style.backgroundImage);
}
window.onload=init;
</script>
</head>

<body>
<div id="test"></div>
</body>
</html>
类似这样试试