【问题标题】:How to get background image URL of an element using JavaScript?如何使用 JavaScript 获取元素的背景图片 URL?
【发布时间】:2012-12-10 09:22:56
【问题描述】:

如何在 JavaScript 中获取 <div> 元素的 background-image URL? 例如,我有这个:

<div style="background-image:url('http://www.example.com/img.png');">...</div>

我如何只获得background-image 的网址?

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    你可以试试这个:

    var img = document.getElementById('your_div_id'),
    style = img.currentStyle || window.getComputedStyle(img, false),
    bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
    

    // Get the image id, style and the url from it
    var img = document.getElementById('testdiv'),
      style = img.currentStyle || window.getComputedStyle(img, false),
      bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
    
    // Display the url to the user
    console.log('Image URL: ' + bi);
    &lt;div id="testdiv" style="background-image:url('http://placehold.it/200x200');"&gt;&lt;/div&gt;

    编辑:

    基于@Miguel 和下面的其他 cmets,如果您的浏览器(IE/FF/Chrome...)将其添加到 url,您可以尝试删除额外的引号:

    bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
    

    如果可能包含单引号,请使用:replace(/['"]/g, "")

    DEMO FIDDLE

    【讨论】:

    • 不幸的是,这在 IE 上不起作用,因为返回的字符串被引用了。所以我最终得到了这个:bi = style.backgroundImage.slice(4, -1).replace(/"/g, ""); 现在可以工作了:)
    • Firefox 也引用了字符串。至少从 FF39 开始。
    • style.backgroundImage.slice(5, -2) 当然也可以。
    • 切片??我觉得自己像个中世纪的农民
    • 这很好,回答了 9 年前 OP 的问题,但请注意,如果 backgroundImagelinear-gradient,它将无法工作;例如:background-image: linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)), url(https://my.image.com);
    【解决方案2】:

    只是补充一点,以防其他人有类似的想法,您也可以使用正则表达式:

    var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];
    

    然而,根据 jsPerf 的说法,@Praveen 的解决方案实际上在 Safari 和 Firefox 中表现更好:http://jsperf.com/match-vs-slice-and-replace

    如果您想考虑值包含引号但不确定是双引号还是单引号的情况,您可以这样做:

    var url = backgroundImage.slice(4, -1).replace(/["']/g, "");
    

    【讨论】:

    • 这是完整的答案
    • | 在您的正则表达式中不是必需的,[...] 表示其中的任何字符。 replace(/["']/g, "") 可以
    【解决方案3】:

    试试这个:

    var url = document.getElementById("divID").style.backgroundImage;
    alert(url.substring(4, url.length-1));
    

    或者,使用replace

    url.replace('url(','').replace(')','');
    // Or...
    backgroundImage.slice(4, -1).replace(/["']/g, "");
    

    【讨论】:

    • 这个子字符串只是删除了url(。它不会删除引号。替换不适用于双引号。使用子字符串 and 替换是可以的,但不会处理双引号。 backgroundImage.slice(4, -1).replace(/["']/g, ""); 就是你要找的东西
    • @narthur157 同意并更新,但这是一个 7 岁的答案。 ?
    【解决方案4】:

    首先你需要返回你的背景图片内容:

    var img = $('#your_div_id').css('background-image');
    

    这将返回如下 URL:

    "url('http://www.example.com/img.png')"

    然后您需要删除此 URL 中不需要的部分:

    img = img.replace(/(url\(|\)|")/g, '');
    

    【讨论】:

      【解决方案5】:

      const regex = /background-image:url\(["']?([^"']*)["']?\)/gm;
      const str = `<div style="background-image:url('http://www.example.com/img.png');">...</div>`;
      let m;
      
      while ((m = regex.exec(str)) !== null) {
          // This is necessary to avoid infinite loops with zero-width matches
          if (m.index === regex.lastIndex) {
              regex.lastIndex++;
          }
          
          // The result can be accessed through the `m`-variable.
          m.forEach((match, groupIndex) => {
              console.log(`Found match, group ${groupIndex}: ${match}`);
          });
      }

      【讨论】:

        【解决方案6】:

        登录到控制台所有background-image URL,不带括号和引号:

        var element = document.getElementById('divId');
        var prop = window.getComputedStyle(element).getPropertyValue('background-image');
        var re = /url\((['"])?(.*?)\1\)/gi;
        var matches;
        while ((matches = re.exec(prop)) !== null) {
            console.log(matches[2]);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-26
          • 1970-01-01
          • 2018-10-23
          • 1970-01-01
          • 2014-04-02
          • 1970-01-01
          • 2020-12-23
          • 2022-11-15
          相关资源
          最近更新 更多