How can I determine the background image URL of a div via JavaScript?

后端 未结 5 914
陌清茗
陌清茗 2020-12-17 22:58

I\'ve found plenty of information on how to change the background image of a div using JavaScript, but I am trying to use JavaScript to determine which background image is b

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 23:28

    You're setting the background property, background and backgroundImage are two seperate properties which is why backgroundImage is empty after setting background. If you want to access just the url part of the background property, you can use the following code:

    var wfBg = document.getElementById("widgetField").style.background;
    var wfBgUrl = wfBg.match(/(url\(['"]?([^)])['"]?\))/i);
    
    if (wfBgUrl)
    {
        // Add your code here. wfBgUrl[1] is full string including "url()", 
        // wfBgUrl[2] would be just the url inside the parenthesis
    }
    

    For styles set by css documents:

    if (window.getComputedStyle) // For standards compliant browsers
        var wfBg = window.getComputedStyle(
            document.getElementById("widgetField")
        ).getPropertyValue("background");
    else // for IE
        var wfBg = document.getElementById("widgetField").currentStyle.background;
    

提交回复
热议问题