读书人

js如何获取背景图片呢?用这个返回的是

发布时间: 2013-04-07 12:50:11 作者: rapoo

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>
类似这样试试

读书人网 >JavaScript

热点推荐