【问题标题】:Javascript get wrong background-image srcJavascript得到错误的背景图像src
【发布时间】:2016-01-17 13:52:27
【问题描述】:

我想在我的服务器上获取图像的自然尺寸,但我没有得到图像的真实来源。

我确实得到了 via jquery 的来源:

.css('background-image').replace('url(','').replace(')','');

但是当我将此 URL 存储到 img.src 中时,它无法获得正确的图像源。

我得到了什么:http://vatocc.net/%22http://vatocc.net/function/file/get/get_file.php?file=/secure/user_img/background_img/1265024466.jpg&purpose=view&format=false%22

真实链接:http://vatocc.net/function/file/get/get_file.php?file=/secure/user_img/background_img/1265024466.jpg&purpose=view&format=false

FIDDLE

更新:

https://jsfiddle.net/7r5yu7ts/1/

【问题讨论】:

  • 第一张图片的链接坏了。
  • 你没有删除引号,这就是它不起作用的原因,并且 URL 被认为是相对的
  • 你得到url("image.png"),在替换你有"image.png"后,用引号,所以当你将它添加到src属性时,它被认为是相对的,而不是绝对的。
  • 需要使用.css('background-image').replace('url("','').replace('")','');去掉双引号
  • 谢谢你们,我确实有错,所以我会再喝一杯咖啡^^

标签: javascript jquery html css url


【解决方案1】:

试试:

var background = $('div').css('background-image'),
imgPath = background.substring(background.lastIndexOf("(")+2,background.lastIndexOf(")")-1);

完整的工作:

var background = $('div').css('background-image'),
    imgPath = background.substring(background.lastIndexOf("(")+2,background.lastIndexOf(")")-1);

var img = new Image;
    img.src = imgPath;
    $('i').html('Source: ' + img.src + 'Width: ' + img.width + ' Height: ' + img.height);

https://jsfiddle.net/7r5yu7ts/3/

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2012-05-23
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多