简体   繁体   English

点击更改边框颜色

[英]change border color on click

I have a menu consisting of 4 div boxes. 我有一个包含4个div盒的菜单。 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? 我需要JavaScript还是CSS?

jsfiddel div jsfiddel div

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;
}

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;
}

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也不支持它。

 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作为参数,因为数字不能用作函数参数

Take a look at this function: 看看这个功能:

http://jqueryui.com/addClass/ http://jqueryui.com/addClass/

It shows how to apply the click event and change the CSS class. 它显示了如何应用click事件并更改CSS类。 You would simply have to create a desired class with border color. 您只需创建一个带边框颜色的所需类。

You can do this via jQuery ( JSFiddle here ): 你可以通过jQuery( JSFiddle here )来做到这一点:

$(document).ready(function() {
  $('.box').click(function() {
    if($('.active').length) {
      $('.active').not($(this)).removeClass('active').addClass('box');
    }      
    $(this).removeClass('box').addClass('active');     
  }); 
});

尝试这个:

.box:focus{ border-color:#cd3232; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM