Skip to content

Instantly share code, notes, and snippets.

@UncleBill
Created May 4, 2018 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UncleBill/ca2e8c8f8206426d3284561c2d85dcd3 to your computer and use it in GitHub Desktop.
Save UncleBill/ca2e8c8f8206426d3284561c2d85dcd3 to your computer and use it in GitHub Desktop.
解析相对 css 文件的图片路径
/**
* 解析相对 css 文件的图片路径
*
* @param baseurl
* @returns {undefined}
*/
function resolveTo (baseurl) {
return function (relativePath) {
// 绝对路径
if (relativePath[0] === '/') {
return location.origin + relativePath[0]
} else if (relativePath.startsWith('data:')) {
return relativePath
}
let url = new URL(baseurl)
let origin = url.origin
let segs = `${origin}${url.pathname}`.split('/')
segs.pop() // 去掉文件名
let relativeSegs = relativePath.split('/')
let seg
do {
seg = relativeSegs[0]
if (seg === '.') {
relativeSegs.shift()
} else if (seg === '..') {
relativeSegs.shift()
segs.pop()
} else {
break;
}
} while (seg)
return segs.concat(relativeSegs).join('/')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment