开发者

jQuery returns 'none' for background-image css value

I am trying to get the value of an elements background-image url. This is set in an external css file. The following always returns, 'none'.

$(".navHeader").each(function() {

                alert($(this).css("background-image"));

            });

css:

    .navHeader {
background-image:url("../../../../commondata/sharedimages/summary/NavBox_topMiddle.png");
background-repeat:no-repeat;
font-family:Arial,Helvetica,san-serif;
font-size:14px;
font-weight开发者_运维技巧:normal;
line-height:16px;
text-align:center;
text-decoration:none;
}


JavaScript uses camelCased CSS property names when they would otherwise be hyphenated. So, background-image becomes backgroundImage.

alert($(this).css("backgroundImage"));


Make sure that you put your code in load event which fires after even images are loaded:

$(window).load(function(){
  $(".navHeader").each(function() {
    alert($(this).css("background-image"));
  });
});


Try using attr instead of css.


According to jQuery documentation @ http://api.jquery.com/css/ you should be able to use either variation.

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css( "background-color" ) and .css( "backgroundColor" ).

Ensure that you don't have anything else on your page that may be affecting the property prior to your code executing. I was experiencing the same behavior when using a media query stylesheet and it was resetting the CSS property to be "" immediately prior to when my code was firing.

To rule out the document being loaded in time, you could run the same code in the console when the page is fully loaded to see if it still results in 'none'. If not - you'd want to somehow only fire your code after it's been applied/downloaded using one of the document.ready or window.load functions.


Years too late, but I found the same issue today and fixed it by switching .css("background-image") with [0].style.backgroundImage.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜