HTML DOM Location hash 属性
htmlweb developmentfront end technology更新于 2025/7/17 20:28:17
Location hash 属性返回/附加一个字符串值(锚点部分)到 URL。锚点部分会自动以 # 开头,然后附加到 URL 中。
语法
以下是语法 −
- hash 属性的返回值
location.hash
- hash 属性集的值
location.hash = ‘string’
示例
让我们看一个 Location hash 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<title>Location hash</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Location-hash</legend>
<label for="urlSelect">Current URL:</label>
<input type="url" size="27" id="urlSelect" value="https://www.example.com/">
<input type="text" id="textSelect" placeholder="hash value...">
<input type="button" onclick="setHashValue()" value="Go To URL">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
var textSelect = document.getElementById("textSelect");
function setHashValue() {
if(textSelect.value !== ''){
location.hash = textSelect.value;
urlSelect.value += location.hash;
divDisplay.textContent = 'Page loaded. Current URL active';
} else {
divDisplay.textContent = 'Please provide a hash value';
}
}
</script>
</body>
</html>
输出
这将产生以下输出 −
点击 ‘转到网址 按钮 − 之前

点击 ‘转到网址 按钮并设置哈希值后 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

