【发布时间】:2008-11-01 04:08:14
【问题描述】:
我用的方法
$("#dvTheatres a").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
有没有更优雅的方法?(单行)
【问题讨论】:
标签: jquery
我用的方法
$("#dvTheatres a").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
有没有更优雅的方法?(单行)
【问题讨论】:
标签: jquery
为什么不直接使用 CSS?
#dvTheatres a {
text-decoration: none;
}
#dvTheatres a:hover {
text-decoration: underline;
}
【讨论】:
您可能会遇到其他 CSS 规则覆盖您想要的规则的问题。即使它在文件中最后声明,其他声明也可能更重要,因此您将被忽略。例如:
#myDiv .myClass a {
color: red;
}
#myDiv a {
color: blue;
}
因为第一条规则更具体,所以它优先。这是一个解释 CSS 特异性的页面:http://www.htmldog.com/guides/cssadvanced/specificity/
您的 jQuery 解决方案有效的原因是因为通过 style="" 参数应用样式具有非常高的特异性。
找出正在应用哪些规则以及哪些规则被其他人否决的最佳方法是使用 Firefox 的 Firebug 扩展。检查其中的元素并单击 CSS 选项卡:它会显示正在应用的每一个 CSS 声明,并在被否决的声明上加上删除线。
如果您想要一种真正快速简便的方法来解决您的问题,请尝试以下方法:
#dvTheatres a:hover {
text-decoration: underline !important;
}
如果你真的想坚持使用 jQuery,你的方法很好,而且可能是最优雅的方法(使用 jQuery)。
【讨论】:
没有好的答案,但也许您只是在寻找替代方案。一种是使用命名函数(和 CSS)来表达意图,而不是内联原始指令。
脚本
function toggleUnderline() { $(this).toggleClass('underline') };
$("#dvTheatres a").hover(toggleUnderline, toggleUnderline);
CSS
.underline { text-decoration: underline; }
【讨论】:
试试这个
$('.my-awesome div a').hover().css('text-decoration', 'none');
【讨论】: