jQuery 在鼠标悬停时添加边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/948781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add border on mouseover
提问by Ankur
I want to have a table border (which I can set using css, rather than the inline border= attribute) to be set to border: 1px solid black; when I mouseover the table.
我想将表格边框(我可以使用 css 设置,而不是内联边框 = 属性)设置为边框:1px 纯黑色;当我将鼠标悬停在桌子上时。
How do I go about doing this in jQuery. I think it's identical to what's happening to the buttons at the top of this page (Questions, Tags, Users etc) except that is a div having it's background color changing whereas I want to change the border of a table. But the concept is the same.
我如何在 jQuery 中执行此操作。我认为这与此页面顶部的按钮(问题、标签、用户等)发生的情况相同,只是 div 的背景颜色发生了变化,而我想更改表格的边框。但概念是一样的。
回答by Philippe Leybaert
For hovering effects, jQuery provides the hover() pseudo-event, which behaves better than moueseenter/mouseleave. Also, it's a good idea to create a CSS class for each state (normal and hovered), and then change the class on hover:
对于悬停效果,jQuery 提供了 hover() 伪事件,其表现优于 moueseenter/mouseleave。此外,最好为每个状态(正常和悬停)创建一个 CSS 类,然后在悬停时更改类:
$(document).ready(function() {
$("#tableid").hover(
function() { $(this).addClass("Hover"); },
function() { $(this).removeClass("Hover"); }
);
});
Your CSS could look like this:
您的 CSS 可能如下所示:
table.Hover { border: 1px solid #000; }
回答by Matthew James Taylor
It may be better to swap classes on the table instead of editing the CSS properties directly - that would be a more scalable/extendable solution:
最好在表上交换类而不是直接编辑 CSS 属性 - 这将是一个更具可扩展性/可扩展性的解决方案:
table {
border:0;
}
table.border {
border:1px solid #000;
}
Of course your table will 'jump' in position 1px when the border is added so maybe it's better to use margin or a white border when you are not hovering:
当然,当添加边框时,您的表格会在 1px 位置“跳跃”,因此当您不悬停时,最好使用边距或白色边框:
table {
border:1px solid #fff;
}
table.border {
border:1px solid #000;
}
Or best yet, if you don't need to be compliant with IE6 you can do it all with pure CSS:
或者最好的是,如果您不需要与 IE6 兼容,您可以使用纯 CSS 完成所有操作:
table {
border:1px solid #fff;
}
table:hover {
border:1px solid #000;
}
This would be the best/simplest/scalable approach!
这将是最好/最简单/可扩展的方法!
回答by Tim M. Hoefer
Alternatively, "outline" as opposed to "border" will not take up extra space in the element layout.
或者,与“边框”相对的“轮廓”不会在元素布局中占用额外的空间。
回答by Michael La Voie
Check out this article on the mouseenter and mouseleave events.
查看有关mouseenter 和 mouseleave 事件的这篇文章。
$("table#mytable").mouseenter(function(){
$("table#mytable",this).css("border", "solid 1px black");
}).mouseleave(function(){
$("table#mytable",this).css("border", "o");
});