开发者

background image problem with javascript

开发者 https://www.devze.com 2022-12-18 21:50 出处:网络
i have problem to fetch background url of a div HTML: <div id=\'test\'></div> CSS: #test { position:absolute; height:55px; width:85px; top:554px; left:197px;background:url(\'images/1.

i have problem to fetch background url of a div

HTML:

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

CSS:

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

when i try to get background image url by using below it displays blank.

a开发者_运维问答lert(document.getElementById("test").style.backgroundImage);

but interestingly it works for following

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

Note: No problem with url because image displayed properly


you can't get the style information from a external CSS since JS only looks into the DOM. I'm not sure if its possible but you should be able to get and modify the CSS information when you set it directly on the element by the style tag:

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


Yes, it's possible, but you'll need the element always:

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

This should return an associative array with all the styles of the given element.

In many cases, funnily enough, it's not possible to access a CSS style directly from JavaScript, as you tried to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消