2013-03-26 69 views
0

我有一大堆的悬停功能,这做同样的紧凑悬停功能

$('#101').mouseover(function() { 
     $('#p1_101').stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $('#p1_101').stop().animate({"fill-opacity": .7}, 200); 
}); 
$('#102').mouseover(function() { 
     $('#p1_102').stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $('#p1_102').stop().animate({"fill-opacity": .7}, 200); 
}); 
$('#103').mouseover(function() { 
     $('#p1_103').stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $('#p1_103').stop().animate({"fill-opacity": .7}, 200); 
}); 

如何在一个函数写这篇文章?

HTML

thwre是一个表,....

和SVG路径有哪些,每一个不同的是,它是不可能在这里显示它

+0

也显示HTML。 – 2013-03-26 11:23:43

+0

所有的选择器都是'id',为什么不使用'class'? – egig 2013-03-26 11:23:49

+0

你的id值无效,[id应该以字母开头](http://www.w3.org/TR/html401/types.html#type-name) – 2013-03-26 11:24:18

回答

0
$.each([1, 2, 3], function (index, value) { 
    $('#10' + value).hover(
    function() { 
     $('#p1_10' + value).stop().animate({"fill-opacity": 1}, 200); 
    }, 
    function() { 
     $('#p1_10' + value).stop().animate({"fill-opacity": .7}, 200); 
    }); 
}); 

UPDATE

$.each(['01', '02', '03'], function (index, value) { 
    $('#1' + value).hover(
    function() { 
     $('#p1_1' + value).stop().animate({"fill-opacity": 1}, 200); 
    }, 
    function() { 
     $('#p1_1' + value).stop().animate({"fill-opacity": .7}, 200); 
    }); 
}); 
+0

是的,这是完美的,thx队友 – gidzior 2013-03-26 11:37:02

+0

很高兴帮助! – 2013-03-26 11:38:31

+0

但如果我有超过10个ID呢?我为每个函数01,02,03添加0,并且从悬停ID中删除0,但它是可以工作的,嘿嘿? – gidzior 2013-03-26 11:47:44

0

怎么样像这样:

function myFunction(var str){ 
    $('#'+str).mouseover(function() { 
     $('#p1_'+str).stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $('#p1_'+str).stop().animate({"fill-opacity": .7}, 200); 
    }); 
    } 

    myFunction('101'); 
    myFunction('102'); 
    myFunction('103'); 
0

我会做一些调整,以标记和JavaScript

HTML(基于给定的情形下的样品)

<div class="my-el" pel="#p1_101">101</div> 
<p id="p1_101">p1</p> 

<div class="my-el" pel="#p1_102">102</div> 
<p id="p1_102">p2</p> 

<div class="my-el" pel="#p1_103">103</div> 
<p id="p1_103">p3</p> 

<div class="my-el" pel="#p1_104">104</div> 
<p id="p1_104">p4</p> 

脚本

$(function(){ 
    $('.my-el').mouseover(function() { 
     $($(this).attr('pel')).stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $($(this).attr('pel')).stop().animate({"fill-opacity": .7}, 200); 
    }); 
}) 

演示:Fiddle

0

如果您在显示的代码中,要动画的元素始终有一个ID为"p1_"加上被徘徊的元素的ID,则可以将相同的函数绑定到所有元素,然后获取通过在功能中使用this.id当前悬停的元素:

$('#101,#102,#103').mouseover(function() { 
     $('#p1_' + this.id).stop().animate({"fill-opacity": 1}, 200); 
    }).mouseout(function() { 
     $('#p1_' + this.id).stop().animate({"fill-opacity": .7}, 200); 
});