2013-08-27 56 views
0

有没有更好的方法来编写下面的代码?JQuery mouseover/mouseout功能 - 更好的代码?

我使用的是Aloha编辑器,在我的jQuery中,任何具有可编辑类的元素都会在mouseover上获得一个3px的虚线边框,下面的代码工作正常,我只是想知道是否存在“最佳实践或者更好的办法”来写这样的代码:

$(function(){ 
    $('[class^="editable"]').mouseover(function(){ 
     $(this).css('border','3px dashed #a7a7a7'); 
    }); 
    $('[class^="editable"]').mouseout(function(){ 
     $(this).css('border','0px dashed #ffffff'); 
    }); 
}); 
+0

为什么你不能使用CSS:悬停选择? – Rebelek

+0

如果您仍然希望为此使用jQuery,那么您可以使用'.hover'事件。它有两个参数函数,一个是光标在元素上方,另一个是光标离开时。 http://api.jquery.com/hover/ –

+0

谢谢你们,我不知道这个功能,我很欣赏 – Michel

回答

3

避免链接的方法调用$()用相同的选择两次:

$('[class^="editable"]').mouseover(function(){ 
    $(this).css('border','3px dashed #a7a7a7'); 
}).mouseout(function(){ 
    $(this).css('border','0px dashed #ffffff'); 
}); 

而不是添加特定的CSS样式表添加这些设置,一个类,然后添加和r EMOVE类:

$('[class^="editable"]').mouseover(function(){ 
    $(this).addClass('hovered'); 
}).mouseout(function(){ 
    $(this).removeClass('hovered'); 
}); 

(...其中该元素的默认样式将被定义为每什么你在鼠标移出设定。)

+0

智能答案,你将代码和样式保存在它们所属的文件中。 – JonathanRomer

+0

谢谢@JonathanRomer。当然,您可以按照Blender的回答在样式表中完成所有操作,尽管这不适用于旧IE中的所有元素类型(假设任何人仍然关心IE6)。 – nnnnnn

+0

是否因为在样式表中添加类然后在jQuery中调用它更干净? – Michel

4

我会用CSS做:

[class^="editable"]:hover { 
    border: 3px dashed #a7a7a7; 
} 
0
使用

hover,它允许用户指定所述第二函数作为参数,因此不再次选择元件:

$('[class^="editable"]').hover(function(){ 
    $(this).css('border','3px dashed #a7a7a7'); 
}, function() { 
    $(this).css('border','0px dashed #ffffff'); 
}); 
+0

谢谢,这真的很好:) – Michel

1

最好的方式是CSS,因为它更快速和更关注样式和脚本的分离,js也在消耗你的资源。但是,如果你需要支持IE6或降低您不能使用:悬停:)

.editable 
{ 
    border: 0px dashed #fff; 
} 

.editable:hover 
{ 
    border: 3px dashed #a7a7a7; 
}