这是html:
<map name="Map" id="Map">
<area id="1" shape="poly" coords="604,140,657,140,677,160,677,234,605,234" />
<area id="2" shape="poly" coords="541,141,593,141,593,207,541,207" />
<area id="3" shape="poly" coords="436,141,486,141,486,207,436,206" />
<area id="4" shape="poly" coords="163,148,163,170,159,170" />
<area id="5" shape="poly" coords="163,207,153,207,159,173,163,173" />
</map>
<div id="pop-up1">Area 1</div>
<div id="pop-up2">Area 2</div>
<div id="pop-up3">Area 3</div>
<div id="pop-up4">Area 4</div>
<div id="pop-up5">Area 5</div>
这是jQuery,它在鼠标悬停时为单个元素显示弹出窗口(它工作正常)
<style>
div#pop-up1{
display: none;
position: absolute;
width: auto;
padding: 10px;
background: #eeeeee;
color: #000000;
border: 1px solid #1a1a1a;
font-size: 90%;
}
</style>
<script>
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('area#1').hover(function(e) {
$('div#pop-up1').show();
//.css('top', e.pageY + moveDown)
//.css('left', e.pageX + moveLeft)
//.appendTo('body');
}, function() {
$('div#pop-up1').hide();
});
$('area#1').mousemove(function(e) {
$("div#pop-up1").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
</script>
});
但是如果我将它循环以获取更多元素,那么它就不起作用
<script type="text/javascript">
$(function() {
var moveLeft = 20;
var moveDown = 10;
for(var p=1; p<3; p++){
$("area#"+p).hover(function(e) {
$("div#pop-up"+p).show();
//.css('top', e.pageY + moveDown)
//.css('left', e.pageX + moveLeft)
//.appendTo('body');
}, function() {
$("div#pop-up"+p).hide();
});
$("area#"+p).mousemove(function(e) {
$("div#pop-up"+p).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}
});
</script>
答案 0 :(得分:1)
您需要为p
提供不同的范围。
for (var p = 1; p < 3; p++) {
(function (p) {
$("area#" + p).hover(function (e) {
$("div#pop-up" + p).show();
}, function () {
$("div#pop-up" + p).hide();
});
$("area#" + p).mousemove(function (e) {
$("div#pop-up" + p).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}(p));
}
另一种解决方案是根据您的情况使用this.id
。
for (var p = 1; p < 3; p++) {
$("area#" + p).hover(function (e) {
$("div#pop-up" + this.id).show();
}, function () {
$("div#pop-up" + this.id).hide();
});
$("area#" + p).mousemove(function (e) {
$("div#pop-up" + this.id).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}