我可以获得 div 的背景图像 url 吗?

发布于 2024-12-26 06:53:20 字数 95 浏览 3 评论 0原文

我有一个按钮,当我单击它时,我想提醒 #div1background-image URL。

是否可以?

I have a button of which when I click it I want to alert the background-image URL of #div1.

Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

韬韬不绝 2025-01-02 06:53:20

如果可能的话,我通常更喜欢 .replace() 而不是正则表达式,因为它通常更容易阅读: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
        alert(bg);
    });

I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
        alert(bg);
    });
请持续率性 2025-01-02 06:53:20

是的,这是可能的:

$("#id-of-button").click(function() {
    var bg_url = $('#div1').css('background-image');
    // ^ Either "none" or url("...urlhere..")
    bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);
    bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""
    alert(bg_url);
});

Yes, that's possible:

$("#id-of-button").click(function() {
    var bg_url = $('#div1').css('background-image');
    // ^ Either "none" or url("...urlhere..")
    bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);
    bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""
    alert(bg_url);
});
不交电费瞎发啥光 2025-01-02 06:53:20

我稍微改进了答案,它处理扩展的 CSS 定义,例如:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript 代码:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

结果:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"

I have slightly improved answer, which handles extended CSS definitions like:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript code:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

Result:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"
煮酒 2025-01-02 06:53:20

正如已经提到的,Blazemongers 解决方案无法删除引号(例如由 Firefox 返回)。因为我发现 Rob Ws 的解决方案相当复杂,所以在这里添加我的 2 美分:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})

As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})
难忘№最初的完美 2025-01-02 06:53:20

我认为为此使用正则表达式是错误的,主要是因为

  • 任务的简单性
  • 运行正则表达式总是比切割字符串更占用CPU/更长。

由于 url("") 组件是不变的,请像这样修剪字符串:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});
梦年海沫深 2025-01-02 06:53:20

我正在用这个

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }
┈┾☆殇 2025-01-02 06:53:20

这是一个简单的正则表达式,它将从返回的字符串中删除 url(" and ")

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");
蓝戈者 2025-01-02 06:53:20

仅使用一次 replace 调用(正则表达式版本):
<代码>
var bgUrl = $('#element-id').css('背景图像').replace(/url\(("|')(.+)("|')\)/gi, '$2' );

Using just one call to replace (regex version):

var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');

一曲琵琶半遮面シ 2025-01-02 06:53:20

我的两分钱。
如果 CSS 中的 background-image 属性被 background 属性覆盖,那么这些解决方案都不起作用。
假设您设置了 background-image 属性,并且您不想在浏览器中看到它,您只需要出于某种目的在 jQuery 中获取该值。
因此,如果您有这样的内容:

<div class="myDivWithBackground">
 <p>Lorem Ipsum</p>
</div>
<style>
.myDivWithBackground{
 background-image: URL('url-here.jpg')
}
div.myDivWithBackground{
 background: #fff!important
}
</style>

$('div').css('background-image'); 返回 none网址。

如果您需要将背景保持为白色,并在 jQuery 中获取background-image URL值,则替换背景伪元素,如下所示:

<style>
    .myDivWithBackground{
     background-image: URL('url-here.jpg')
    }
    div.myDivWithBackground:after{
      content: '';
      display: block;
      width: 100%;
      height: 100%;
      background: #fff;
      top: 0;
      position: absolute;
    }
    div.myDivWithBackground p{
      position: relative;
      z-index: 9999;
    }
</style>

现在 $('div').css('background-image'); 返回URL('url-here.jpg'),而不是

My two cents.
None of these solutions work if the background-image property is overwritten in CSS by the background property.
Let's say you have the background-image property set and you don't want to see it in the browser, you just need to get the value in jQuery for some purpose.
So, if you have something like this:

<div class="myDivWithBackground">
 <p>Lorem Ipsum</p>
</div>
<style>
.myDivWithBackground{
 background-image: URL('url-here.jpg')
}
div.myDivWithBackground{
 background: #fff!important
}
</style>

Then $('div').css('background-image'); returns none instead the URL.

If you need to keep background white and also to get the background-image URL value in jQuery then replace the background with pseudo-element, like this:

<style>
    .myDivWithBackground{
     background-image: URL('url-here.jpg')
    }
    div.myDivWithBackground:after{
      content: '';
      display: block;
      width: 100%;
      height: 100%;
      background: #fff;
      top: 0;
      position: absolute;
    }
    div.myDivWithBackground p{
      position: relative;
      z-index: 9999;
    }
</style>

Now $('div').css('background-image'); returns URL('url-here.jpg') instead none.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文