why this css transition doesn't work

StackOverflow https://stackoverflow.com/questions/20301753
  •  
  •  | 
  •   ( words)
 检查

问题

.box {
  width: 150px;
  height: 150px;
  background: red;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  -webkit-transition: background-color 0.3 ease-out;
  -moz-transition: background-color 0.3s ease-out;
  -o-transition: background-color 0.3s ease-out;
  transition: background-color 0.3s ease-out;
      opacity:0.2;
}

.box:hover {
  cursor: pointer;
  opacity:1;
}

I try to do a transition with opacity, it doesn't work, but it can work if I do the background change effect.

demo http://jsfiddle.net/rsg4e/

解决方案 3

Write

transition: opacity 0.3 ease-out;

Instead of

transition: background-color 0.3 ease-out;

Because on hover you are changing opacity not background.

.box {
  width: 150px;
  height: 150px;
  background: red;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  -webkit-transition: opacity 0.3 ease-out;
  -moz-transition: opacity 0.3s ease-out;
  -o-transition: opacity 0.3s ease-out;
  transition: opacity 0.3s ease-out;
      opacity:0.2;
}

DEMO

其他提示

You were on the right track - just went the wrong way.

Fixed your fiddle

What you wanted was the background-color to change opacity, not the full element and whatever might be inside of it. All you need to do is set the backgrounds to rgba() values and you're set.

.box {

  background-color: rgba(255,0,0,0.2);

}
.box:hover {

  background-color: rgba(255,0,0,1);

}

Of course - if you ACTUALLY want everything inside of it to change opacity as well, then go with one of the other answers - they hit it on the head.

You're setting a transition on the background-color, when you should be calling it on the opacity i.e:

-webkit-transition: opacity 0.3s ease-out;

There's not a background-color property to transition because you've specified it as background. so naturally the transition wont work.

Change it to :

-webkit-transition: background 0.3 ease-out;
  -moz-transition: background 0.3s ease-out;
  -o-transition: background 0.3s ease-out;
  transition: background 0.3s ease-out;

or

-webkit-transition: all 0.3 ease-out;
  -moz-transition: all 0.3s ease-out;
  -o-transition: all 0.3s ease-out;
  transition: all 0.3s ease-out;

and your hover state to

.box:hover { background: /*younewcolor*/;}

and everything should should work fine.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow