所以我在html / css / javascript中制作了一个映射图像。 我这样做是因为当我点击一个区域时,一个函数被调用,使得一个模态出现,内容取决于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>
答案 0 :(得分:1)
问题是你的函数在更改之前获取了location.hash。要修复它,您必须直接从您单击的元素中获取哈希值。
我已经为解决方案添加了一个codepen:
<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>
function appearModal(event) {
var hash = event.target.hash;
switch (hash) {
case "#topright":
console.log(hash);
break;
case "#bottomright":
console.log(hash);
break;
case "#bottomleft":
console.log(hash);
break;
case "#topleft":
console.log(hash);
break;
default:
console.log(hash);
}
}
答案 1 :(得分:0)
试试这个:
function appearModal(event) {
setTimeout(function() {
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);
}
}, 10);
}
发生这种情况是因为浏览器首先执行你的onclick函数,然后更改散列,所以你总是得到前一个散列。
代码的工作原理是先让哈希值发生变化,然后执行onclick函数,因为setTimeout可以让其他程序先执行,直到进程空闲