我正在为一个公司的推广建立一个网站,有24个地图形状的“热点”在页面上打开24个单独的div。不是我的设计,但我还不够高,不能为我的案子辩护,所以我会同意的。一个同事写的代码是可怕的(至少我这么认为)--
$(".hover1").mouseenter(function(){
$(".winner1").fadeIn();
}).mouseleave(function(){
$(".winner1").stop().fadeOut();
});(x24)
所有24个不同的“热点”和div。所以你可以想象每个人都变成了".hover2",".hover3“等等.".winner2“、".winner3”等也是如此.
这段代码大约有120行。
我的问题,因为我不是一个jQuery专家从长远来看,是如何简化这一点?我知道一定有办法,我只是不知道。
每个div和热点都被标记为"hover1“/ "winner1”、"hover2“/ "winner2”等,并以这种方式连接起来。
任何帮助都将不胜感激,谢谢您的帮助!!
:-)
编辑
这是HTML
为了地图
<map name="Map">
<area shape="rect" coords="6,1,258,232" class="hover1"/>
</map> 所以当你在上面盘旋时,它就会出现。
<div class="winner1 badge male">
<div class="winnerText">
<p><span>Winner:</span> Clay Cauley</p>
<p><span>Date:</span> December 3<sup>rd</sup>, 2012</p>
<p><span>Prize:</span> XBOX 360</p>
</div>
</div>发布于 2012-11-28 15:15:30
假设您可以修改HTML,请尝试如下:
<map name="Map">
<area shape="rect" coords="6,1,258,232" class="hover" data-target="winner1" />
<area shape="rect" coords="2,2,2,2" class="hover" data-target="winner2" />
<area shape="rect" coords="3,3,3,3" class="hover" data-target="winner3" />
<area shape="rect" coords="4,4,4,4" class="hover" data-target="winner4" />
<area shape="rect" coords="5,5,5,5" class="hover" data-target="winner5" />
</map> $(".hover").hover(function() {
$("." + $(this).data("target")).fadeIn();
},
function() {
$("." + $(this).data("target")).stop().fadeOut();
});发布于 2012-11-28 15:05:33
不要为.hover和.winner创建惟一的类,而要执行如下标记:
<div class="container">
<div class="hover">
Hovercontent #1
</div>
<div class="winner">
Winnercontent #1
</div>
</div>
<div class="container">
<div class="hover">
Hovercontent #2
</div>
<div class="winner">
Winnercontent #2
</div>
</div>然后像这样写你的javascript。
$('.hover').on('mouseenter', function() {
$(this).siblings('.winner').fadeIn();
}.on('mouseleave', function() {
$(this).siblings('.winner').stop().fadeOut();
});发布于 2012-11-28 15:10:14
您可以将mousenter和mouseleave事件附加到所有热点,并确定函数中应该显示/隐藏哪个div。这假设当您说它们是“标签”时,就意味着它是id或其他一些HTML属性。就像-
$("map").mouseenter(function(event){
var index = [some function to find the index of the event.target]; // For example, the index of "hover1" is 1
$("winner" + index).fadeIn();
}).mouseleave(function(event){
var index = [some function to find the index of the event.target];
$("winner" + index).stop().fadeOut();
})Javascript字符串解析函数应该很容易找到,以便从id或类似的地方完成索引解析。
https://stackoverflow.com/questions/13608041
复制相似问题