【发布时间】:2018-07-04 16:33:55
【问题描述】:
所以我在 html/css/javascript 中制作了一个映射图像。 我这样做了,所以当我单击一个区域时,调用了一个函数 get 来显示一个模式,内容取决于 location.hash 由于映射区域中的 href 属性而发生变化。 问题是,它始终是前一个哈希,而不是当前哈希, 例如:
- #hash1
- #hash2, location.hash returns: #hash1
- #hash3, location.hash returns: #hash2
- #hash4, location.hash returns: #hash3
- #hash5, location.hash returns: #hash4
- #hash6, location.hash returns: #hash5
- #hash7, location.hash returns: #hash6
etc.
这是为什么呢?我该如何解决这个问题?
我使用的代码总结:
<img src="image.png" width="300" height="300" usemap='#modalmap'>
<map name="modalmap">
<area shape="rect" coords="0,0,150,150" alt="topleft" href="#topleft" target="_self" title="topleft" onclick="appearModal(event)">
<area shape="rect" coords="150,0,300,150" alt="topright" href="#topright" target="_self" title="topright" onclick="appearModal(event)">
<area shape="rect" coords="0,150,150,300" alt="bottomleft" href="#bottomleft" target="_self" title="bottomleft" onclick="appearModal(event)">
<area shape="rect" coords="150,150,300,300" alt="bottomright" href="#bottomright" target="_self" title="bottomright" onclick="appearModal(event)">
</map>
<script>
function appearModal(event){
switch(location.hash){
case "#topright":
console.log(location.hash);
break;
case "#bottomright":
console.log(location.hash);
break;
case "#bottomleft":
console.log(location.hash);
break;
case "#topleft":
console.log(location.hash);
break;
default:
console.log(location.hash);
}
</script>
【问题讨论】:
-
我建议收听
window.onhashchange而不是在点击后获取哈希(当它尚未设置时)
标签: javascript html css anchor location-href