2012-12-10 38 views
2

我拿起一些代码在这里(不记得链接),但我想看看它是否可以优化。我有一张桌子,第一排有一张图片。在第二行中,当鼠标悬停在上方时,顶部的图像会发生变化。我的JSFiddle现在正在使用颜色。我稍后会交换图像。如何优化jQuery代码悬停元素,影响另一个元素

行现在只有3个单元格,但是一旦我找到了它们,它们可能会包含12个单元格,因此我需要在将鼠标悬停在所有这些单元格上时显示不同的图像。

该代码有效,但我认为如果达到12个单元格/盒,效率不会很高。这个代码如何优化?

// box 1 
$('#whybox1').mouseover(function(){ 
    $('#whybox1').css('background-color', '#F7FE2E'); 
    $('#animalbox').css('background-color', '#F7FE2E'); 
}); 
$('#whybox1').mouseout(function(){ 
    $('#whybox1').css('background-color', '#d1e6f8'); 
    $('#animalbox').css('background-color', '#d1e6f8'); 
}); 

作为一个方面来看,我已经看到了这样的一个用正实现:孩子,但是那大干快上,我必须支持旧的浏览器打破。

http://jsfiddle.net/ccamacho/WfJvh/

回答

1
<table> 
<tr> 
<td colspan="3" id="animalbox">Animal Box</td> 
</tr> 
<tr id="boxes"> 
<td class="box" data-hoverColor="#F7FE2E" id="whybox1">1</td> 
<td class="box" data-hoverColor="#F6CEE3" id="whybox2">2</td> 
<td class="box" data-hoverColor="#81F7BE" id="whybox3">3</td> 
</tr> 
</table>​ 


$('#boxes').on('mouseenter mouseleave', '.box', function(e) { 
if (e.type === 'mouseenter') { 
    console.log() 
    $(this).css('background-color', $(this).data('hoverColor')); 
    $('#animalbox').css('background-color', $(this).data('hoverColor')); 
} 
else { 
    $(this).css('background-color', '#d1e6f8'); 
    $('#animalbox').css('background-color', '#d1e6f8'); 
} 
}); 

的jsfiddle:http://jsfiddle.net/WfJvh/4/

+0

这不是有效的HTML属性。使用data- *替代... – Neysor

+1

将属性更改为html5中提供的数据模型,如Neysor指出的那样。 –

1

是否有你需要使用mouseovermouseout,而不是仅仅hover理由吗?如果你不必担心IE6,那么你可以在CSS中使用:hover来交换你的样式。

#whybox1:hover { 
    background-color: #d1e6f8; 
} 
#whybox1:hover { 
    background-color: #F7FE2E; 
} 

如果您需要在图像上添加图像并且它不能成为背景图像,那么您需要使用JS。我建议是这样的:

$('#whybox1').hover(function() { 
    // this happens when you hover over the element 
    $(this).addClass('hover'); 
}, 
function() { 
    // this happens when you're no longer hovering over the element 
    $(this).removeClass('hover'); 
}); 

只需添加一个类,并修改元素样式时所应用到的类,然后徘徊结束时删除类。

即使您决定使用鼠标悬停/悬停,它并不是低效的 - 您是怎么想的?除非您将这些事件附加到数百个(可能是数千个)元素上,否则您将看不到性能问题。不管你如何去做,12个表格单元都会很好。如果可能的话,我会建议使用CSS。

2

也许这样的事情

http://jsfiddle.net/WfJvh/5/

这就是做这个只是其中一种方法。这个想法是,你添加到td某些属性,它将保存一些信息(在这种情况下是彩色的)并在悬停时使用该信息。

的Javascript:

$(window).load(function(){ 
    $(document).ready(function(){ 
     $('table td').mouseover(function(){ 
      var color = $(this).attr('data-color'); 
      $(this).css('background-color', color); 
      $('#animalbox').css('background-color', color); 
     }); 
     $('table td').mouseout(function(){ 
      $(this).css('background-color', '#d1e6f8'); 
      $('#animalbox').css('background-color', '#d1e6f8'); 
     }); 
    }); 
});​ 

HTML:

<table> 
<tr> 
<td colspan="3" id="animalbox">Animal Box</td> 
</tr> 
<tr> 
<td id="whybox1" data-color="red">1</td> 
<td id="whybox2" data-color="blue">2</td> 
<td id="whybox3" data-color="green">3</td> 
</tr> 
</table>​ 
相关问题