developer tip

자바 스크립트 : 배경 이미지 URL 가져 오기

optionbox 2020. 12. 12. 10:39
반응형

자바 스크립트 : 배경 이미지 URL 가져 오기


JavaScript background-image에서 <div>요소 URL을 어떻게 얻 습니까? 예를 들어 다음과 같습니다.

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

어떻게 얻을 것입니다 단지 의 URL을 background-image?


이것을 시도 할 수 있습니다.

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);
<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>

편집하다:

@Miguel 및 아래의 기타 의견을 기반으로 브라우저 (IE / FF / Chrome ...)가 URL에 추가하는 경우 추가 따옴표를 제거 할 수 있습니다.

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

작은 따옴표를 포함 할 수있는 경우 다음을 사용하십시오. replace(/['"]/g, "")

데모 FIDDLE


다른 사람이 비슷한 아이디어를 가지고있는 경우에 추가하기 위해 Regex를 사용할 수도 있습니다.

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, "");

이 시도:

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, "");

먼저 배경 이미지 콘텐츠를 반환해야합니다.

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

그러면 다음과 같은 URL이 반환됩니다.

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

그런 다음이 URL에서 원하지 않는 부분을 제거해야합니다.

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

참고 URL : https://stackoverflow.com/questions/14013131/javascript-get-background-image-url-of-div

반응형