Created
May 4, 2018 06:57
-
-
Save UncleBill/ca2e8c8f8206426d3284561c2d85dcd3 to your computer and use it in GitHub Desktop.
解析相对 css 文件的图片路径
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 解析相对 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