简体   繁体   中英

CSS add remove border on class toggle

I recently ran into an issue when adding or removing a border based on a adding or removing a class. I have fixed the issue, but I am not satisfied with the solution.

I made a jsfiddle illustrating the problem. Even with transitions on both classes, the border will transition in correctly, but will transition out abruptly.

: The issue is fixed by setting a border property with the same attributes. :通过设置具有相同属性的border属性可以解决此问题。 Setting a "border: 0px solid red;" on .boxy fixes it, but setting just "border: 0px;" does not.

Here is the working jsfiddle code:

<div class="boxy"></div>

.boxy {
   width: 100px;
   height: 100px;
   background-color: black;
   border: 0px solid red;
   -webkit-transition: border 300ms linear 0s;
   -moz-transition: border 300ms linear 0s;
   -o-transition: border 300ms linear 0s;
   transition: border 300ms linear 0s;
}

.selected {
  border: 10px solid red;
}

$('.boxy').click(function(event){
    $('.boxy').toggleClass('selected');
})

Just define the correct border on .boxy and set it's width to 0px .

Like this border: 0px solid red; , so you will apply the transition between 0px and 10px

Explanation

It enables you to define the transition between two states of an element.


Source

So in your case, you've to define the initial state of the border. ( border: 0px solid red )

Fiddle

I think you don't need to add the transition on both classes, try this:

.boxy {
    width: 100px;
    height: 100px;
    background-color: black;
    border: 10px solid #fff;
    -webkit-transition: border 300ms linear 0s;
    -moz-transition: border 300ms linear 0s;
    -o-transition: border 300ms linear 0s;
    transition: border 300ms linear 0s;
}

.selected {
  border: 10px solid red;
}

EDIT : With your new JSFiddle you need this:

.boxy{
   border: 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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