demoncoder demoncoder - 3 months ago 15
CSS Question

hover page background change color fade effect(css or jqeury)

I have tried to figure out to let the background color fade when changing. But fail to do so. Not sure whether I should use css or jqeury. Please have a look, thank you.



.wrapper {
width: 100%;
}

.left-col,
.right-col {
width: 50%;
float: left;
}

a.btn {
background: #fff;
display: inline-block;
}

a.btn:before {
background-color: transparent;
transition: all 0.5s ease;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
}

a.btn:hover:before {
content: '';
position: fixed;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: -1;
}

a.btn.btn-1:hover:before {
background-color: red;
}

a.btn.btn-2:hover:before {
background-color: green;
}

<div class="wrapper">
<div class="left-col">
<a href="#" class="btn btn-1">Button 1</a>
</div>
<div class="right-col">
<a href="#" class="btn btn-2">Button 2</a>
</div>
</div>





Update the jquery fiddle here:
http://jsfiddle.net/rae0724/k3bkbpg7/2/
It's working now, but the place that I hover is not accurate.
It keep on showing green even I didn't hover anything.

Answer

background-color is a CSS transitionable/animatable property.

All I did was set the transition, and used JQuery to add/remove some classes causing the background color of that element to change.

Have a look at my CodePen here: http://codepen.io/jarodsmk/pen/EyAOdN

HTML:

<body>
  <h1>Mouse over a color</h1>
  </br>
  <div class="blue">Blue</div>
  <div class="green">Green</div>
</body>

CSS:

body{
  background-color: red;
  transition: background-color 4s;
}

.blue,body.blue{
  background-color: blue;
}

.green,body.green{
  background-color: green;
}

JS:

$('.blue').hover(function(){
  $('body').addClass('blue');
}, function(){
  $('body').removeClass('blue');
});

$('.green').hover(function(){
  $('body').addClass('green');
}, function(){
  $('body').removeClass('green');
});