从background-image属性中获取URL

时间:2013-11-07 00:50:42

标签: javascript css

如何从background-image属性中获取URL:

现在我这样做:

(window.getComputedStyle(element).getPropertyValue("background-image")).replace('url(','').replace(')','');

但是如果在背景图像中还有像webgradient这样的其他东西,那么我也会得到它们。我怎么能避免这种情况?

4 个答案:

答案 0 :(得分:2)

这里有一种方法可以在不使用核心JS的情况下考虑多个背景图像:

var bg="url(http://css.bbystatic.com/images/_headerFooter/icons-new-e42e71d385bbad8d5c‌​cba0cfeb3983a1.png), -webkit-linear-gradient(top, rgb(255, 242, 0) 0%, rgb(247, 207, 0) 100%)";

var imgUrl=(
        bg.match( /url\([^\)]+\)/gi ) || 
        [""]
    )[0]
    .split(/[()'"]+/)[1];

alert(imgUrl);

imgUrl将是网址或未定义,具体取决于您提供的内容。 它应该是100%crossbrowser / node.js好,没有涉及到dom ......

答案 1 :(得分:2)

这样做:

var m = (window.getComputedStyle(element).getPropertyValue("background-image")).match(/url\(([^)]+)\)/i); 

if (m) { ... m[1] ... }

答案 2 :(得分:0)

试试这段代码,这可能是你需要的正则表达式

/url(\s*\S*\s*)/i

如果列出的正则表达式dandavis可以执行此操作

.match(/url([^)+])/gi).replace('url(','').replace(')','')

答案 3 :(得分:0)

登录控制台所有library(xml2) url <- "https://stats.oecd.org/restsdmx/sdmx.ashx/GetData/FDIINDEX/AUT+BEL.4+5+8+9+14.V.INDEX/all?startTime=1997&endTime=2019" series <- read_xml(url) %>% xml_ns_strip() %>% xml_find_all("//DataSet/Series") # find all Series nodes # note that the easiest way to read nodes in this file is to remove the namespaces by xml_ns_strip() data <- purrr::map_dfr( series, function(x) { data.frame( LOCATION = x %>% xml_find_first(".//Value[@concept='LOCATION']") %>% xml_attr("value"), # for each Series node, get the first Value node has 'concept' attribute is 'LOCATION' and extract the 'value' attribute value SECTOR = x %>% xml_find_first(".//Value[@concept='SECTOR']") %>% xml_attr("value"), RESTYPE = x %>% xml_find_first(".//Value[@concept='RESTYPE']") %>% xml_attr("value"), SERIES = x %>% xml_find_first(".//Value[@concept='SERIES']") %>% xml_attr("value"), TIME_FORMAT = x %>% xml_find_first(".//Value[@concept='TIME_FORMAT']") %>% xml_attr("value"), data.frame( Time = x %>% xml_find_all(".//Obs/Time") %>% xml_text(trim = TRUE) %>% as.integer(), ObsValue = x %>% xml_find_all(".//Obs/ObsValue") %>% xml_attr("value") %>% as.numeric() ) ) } ) URL,不带括号和引号:

background-image