2010-01-28 68 views
0

我有问题获取一个div的背景URL背景图片的问题与JavaScript

HTML:

<div id='test'></div> 

CSS:

#test { position:absolute; height:55px; width:85px; top:554px; left:197px; background:url('images/1.jpg'); } 

当我试图让背景通过使用下面的图像网址显示空白。

alert(document.getElementById("test").style.backgroundImage); 

但有趣的是它适用于以下

document.getElementById("test").style.backgroundImage="url('images/1.jpg')"; 
alert(document.getElementById("test").style.backgroundImage); 

注:没有与URL的问题,因为图像正常显示

回答

1

你不能得到,因为JS一个外部CSS样式信息只看着DOM。我不知道如果可能的,但你应该能够获得和修改CSS的信息,当您在风格标签直接设置它的元素:

<div style="position:absolute; height:55px; width:85px; top:554px; left:197px; background:url('images/1.jpg');"></div> 
1

是的,这是可能的,但你需要元素总是:

function getStyles (element) { 
    element = document.getElementById(element); 
    if (element.currentStyle) { 
     return element.currentStyle; 
    } else if (window.getComputedStyle) { 
     return document.defaultView.getComputedStyle(element, null); 
    } 
} 

这应该返回一个关联数组,其中包含给定元素的所有样式。

在许多情况下,有趣的是,无法像JavaScript那样直接从CSS访问CSS样式。