這里介紹的其實(shí)本質(zhì)上是兩種方法,通過創(chuàng)建DOM或通過JavaScript計(jì)算:
1)通過新創(chuàng)建的Image, 經(jīng)測(cè)試會(huì)發(fā)送一個(gè)Aborted的請(qǐng)求,并且IE6不支持, 將new Image改成document.createElement('IMG')也是一樣的;測(cè)試應(yīng)該不喜歡這個(gè)方案;
復(fù)制代碼 代碼如下:
function getAbsoluteUrl(url){
var img = new Image();
img.src = url; // 設(shè)置相對(duì)路徑給Image, 此時(shí)會(huì)發(fā)送出請(qǐng)求
url = img.src; // 此時(shí)相對(duì)路徑已經(jīng)變成絕對(duì)路徑
img.src = null; // 取消請(qǐng)求
return url;
}
getAbsoluteUrl("showroom/list");
2)創(chuàng)建Anchor(鏈接),這種方法不會(huì)發(fā)出任何請(qǐng)求(請(qǐng)求會(huì)在加入DOM時(shí)產(chǎn)生),但是IE6也不支持
復(fù)制代碼 代碼如下:
/*jslint regexp: true, white: true, maxerr: 50, indent: 2 */
function parseURI(url) {
var m = String(url).replace(/^/s+|/s+$/g, '').match(/^([^://?#]+:)?(////(?:[^:@]*(?::[^:@]*)?@)?(([^://?#]*)(?::(/d*))?))?([^?#]*)(/?[^#]*)?(#[/s/S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
function absolutizeURI(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(/./.?(//|$))+/, '')
.replace(///(/.(//|$))+/g, 'http://www.survivalescaperooms.com/')
.replace(////./.$/, '/../')
.replace(///?[^//]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^///, input.charAt(0) === 'http://www.survivalescaperooms.com/' ? 'http://www.survivalescaperooms.com/' : '');
}
href = parseURI(href || '');
base = parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === 'http://www.survivalescaperooms.com/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? 'http://www.survivalescaperooms.com/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('http://www.survivalescaperooms.com/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
}
由此可見,用原生態(tài)的方法訪問所有的Image, Anchor時(shí),返回的都是絕對(duì)路徑,此時(shí)如果想返回原來的相對(duì)路徑,可以用查詢DOM的方法,如jQuery.attr()方法:
復(fù)制代碼 代碼如下:
//返回絕對(duì)路徑,jQuery對(duì)象實(shí)質(zhì)上是"類數(shù)組"結(jié)構(gòu)(類似arguments),因此使用[0]可以訪問到原生態(tài)的對(duì)象,然后取"href";
console.log($anchor[0]["href"]);
//返回原始路徑
console.log($anchor.attr("href"));
新聞熱點(diǎn)
疑難解答
圖片精選