Window location.href 屬性

定義和用法

location.href 屬性設置或返回當前頁面的整個 URL。

實例

例子 1

獲取當前頁面的 URL:

let url = location.href;

親自試一試

例子 2

設置當前頁面的 URL:

location.href = "";

親自試一試

例子 3

將 href 值設置為指向頁面內的錨點:

location.href = "#top";

親自試一試

例子 4

將 href 值設置為指向電子郵件地址(將打開軟件并創建新電子郵件):

location.href = "mailto:someone@example.com";

親自試一試

語法

返回 href 屬性:

location.href

設置 href 屬性:

location.href = URL

屬性值

描述
URL

絕對 URL,例如:

http://www.example.com/index.html


相對 URL,例如:

index.html


錨 URL,如:

location.href="#top"


新協議,如:

ftp://someftpserver.com

mailto:someone@example.com

file://host/path/example.txt

返回值

類型 描述
字符串 頁面的完整 URL,包括協議(如 https://)。

瀏覽器支持

所有瀏覽器都支持 location.href

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 支持 支持 支持 支持 支持