Html 单击时更改边框颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16846897/
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
change border color on click
提问by kaputu
I have a menu consisting of 4 div boxes. I want the active box to have a red border, if another box is clicked the border is white and the border of the other box is red. Do I need JavaScript or is CSS enough?
我有一个由 4 个 div 框组成的菜单。我希望活动框具有红色边框,如果单击另一个框,则边框为白色,另一个框的边框为红色。我需要 JavaScript 还是 CSS 就足够了?
HTML
HTML
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
CSS
CSS
.box{
margin: 10px;
float: left;
width: 100px;
height: 50px;
background-color: blue;
border: solid 1px red;
}
回答by Adam Waite
For click you'll need JavaScript if you want to maintain the state, hover is OK with CSS.
对于单击,如果要保持状态,则需要 JavaScript,使用 CSS 悬停就可以了。
You can use div:active { /* style */ }
for a click and hold style but it will disappear after mouse up.
您可以使用div:active { /* style */ }
单击并按住样式,但它会在鼠标抬起后消失。
This is a quick way to do it with jQuery:
这是使用 jQuery 快速完成的方法:
$('.box').on('click', function(e){
e.preventDefault();
$(this).css('border-color', 'lime');
});
Probably better to toggle a class though:
不过切换一个类可能更好:
JS:
JS:
$('.box').on('click', function(e){
e.preventDefault();
$(this).toggleClass('myClickState');
});
CSS:
CSS:
.myClickState {
border-color: lime;
}
回答by Zaidi Riyadh
function fnChangeBorder(boxId)
{document.getElementById(boxId).style.border = "solid #AA00FF";}
<div class="box" id="A" onclick="fnChangeBorder('A')">Click here !!</div>
i chose A as a parameter because numbers won't work as a function parameters
我选择 A 作为参数是因为数字不能作为函数参数
回答by Axel
Yes, you can use the :active
pseudo-selector to achieve this.
是的,您可以使用:active
伪选择器来实现这一点。
Try this:
尝试这个:
.box:active {
border-color: red;
}
This, however, will not persist after you release the mouse.
但是,这在您松开鼠标后不会持续存在。
It is also not supported in IE6.
IE6 也不支持它。
回答by Nikita Silverstruk
Take a look at this function:
看看这个函数:
It shows how to apply the click event and change the CSS class. You would simply have to create a desired class with border color.
它展示了如何应用点击事件和更改 CSS 类。您只需创建一个带有边框颜色的所需类。
回答by Dejo Dekic
You can do this via jQuery (JSFiddle here):
您可以通过 jQuery(此处为 JSFiddle)执行此操作:
$(document).ready(function() {
$('.box').click(function() {
if($('.active').length) {
$('.active').not($(this)).removeClass('active').addClass('box');
}
$(this).removeClass('box').addClass('active');
});
});
回答by Alamshaha Shaikh
Try this:
尝试这个:
.box:focus{ border-color:#cd3232; }