这是我的代码:
jQuery:
$(document).ready(function () {
$("#news").hover(function () {
$('#news_img').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news1").hover(function () {
$('#news_img1').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news3").hover(function () {
$('#news_img3').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news4").hover(function () {
$('#news_img4').animate({
height: 'toggle'
}, 290, function () {
});
});
});
JSFIDDLE 在这里:<强> http://jsfiddle.net/huydq91/N89Kw/
我想减少我的代码,以便将来我想添加更多代码时更易于管理 <tr>
或 <td>
无需在 jQuery 和 CSS 中过多编辑标签。
您可以通过其类 news
定位悬停元素,并通过将悬停元素的 id 中的最后数字附加到 news_img
来找到目标元素,例如
$(document).ready(function () {
$(".news").hover(function () {
$('#news_img' + this.id.replace('news', '')).stop(true).animate({
height: 'toggle'
}, 290, function () {});
});
});
演示:Fiddle
您可以通过向图像添加一些 data-* 属性来删除悬停的 css 部分,例如
<img src="http://i853.photobucket.com/albums/ab100/vimeo1903/Showroom1_zps923b43dc.jpg" border="0" alt="Showroom1" data-hover="http://i853.photobucket.com/albums/ab100/vimeo1903/Showroom1_1_zpse41d0851.jpg" />
然后
$(document).ready(function () {
//since the news elements has a common class, use it to target all the news elements instead of using individual ids
$(".news").hover(function (e) {
//you can find the `news_img` within the current news item using .find() instead of using its class to target it
$(this).find('.news_img').stop(true).animate({
height: 'toggle'
}, 290);
//find the image element within the current news
var $img = $(this).find('.imgswap img');
//if the current event is mouseenter then show the hover image else the src image
//the hover handler registers 2 handler one for mouseenter another for mouseleave
$img.attr('src', $img.data(e.type == 'mouseenter' ? 'hover' : 'src'));
});
//when we leaves the news elements we need to put back the original src, so store it using data api
$('.news .imgswap img').each(function () {
$(this).data('src', this.src);
})
});
我是一名优秀的程序员,十分优秀!