html - CSS3 animate only on hover on and off -
i have animation of box, it's width increases on hover:
jsfiddle: https://jsfiddle.net/hbpncv34/
html:
<div></div>
css:
div { background-color: red; height: 10vh; width: 10vw; } div:hover { animation: change_width 0.7s forwards; } @keyframes change_width { { width: 10vw; } { width: 15vw; } }
issue:
i want box smoothly move when hover off of it.
there 2 ways this:
method 1:
jsfiddle: https://jsfiddle.net/hbpncv34/1/
html:
<div></div>
css:
div { background-color: red; height: 10vh; width: 10vw; animation: change_width_back 0.7s forwards; } div:hover { animation: change_width 0.7s forwards; } @keyframes change_width { { width: 10vw; } { width: 15vw; } } @keyframes change_width_back { { width: 15vw; } { width: 10vw: } }
issue:
the change_width_back
animation runs on page load.
also, mousing on / off rapidly not smooth transition
, so:
method 2:
jsfiddle: https://jsfiddle.net/hbpncv34/2/
html:
<div></div>
css:
div { background-color: red; height: 10vh; width: 10vw; transition: width 0.7s; } div:hover { width: 15vw; }
issue:
the animation runs on zooming in , out.
i can fix using px
or %
instead of vw
widths, it's crucial in actual issue keep viewport units.
so, there way play animation on hover on , off, , only hover on , off?
since don't know javascript, please keep answers html / css only. if js absolutely needed, make simple enough copy + paste minimal editing.
thanks help.
there may better way, little js
combined method 1
, can this:
<div onmouseover="this.classlist.add('animate')"></div>
and in css:
div { background-color: red; height: 10vh; width: 10vw; } div.animate { animation: change_width_back 0.7s forwards; }
https://jsfiddle.net/vhyfewnt/
edit
first solution meant work animate, not transition. there's way make transition work, needs little more javascript.
<body onresize="document.getelementsbytagname('div')[0].classlist.add('zoom'); settimeout(function(e){document.getelementsbytagname('div')[0].classlist.remove('zoom')}, 100)"> <div></div> </body> div { background-color: red; height: 10vh; width: 10vw; } div:not(.zoom) { transition: width 0.7s; } div:hover { width: 15vw; }
https://jsfiddle.net/cdj7l5r3/
2nd edit:
to apply more elements, can add class body (or ancestor) , change rule. this:
<body onresize="document.body.classlist.add('zoom'); settimeout(function(e){document.body.classlist.remove('zoom')}, 100)"> <div></div> <div></div> <div></div> <div></div> <section></section> </body> div, section{ background-color: red; height: 10vh; width: 10vw; } body:not(.zoom) div, body:not(.zoom) section { transition: width 0.7s; } div:hover, section:hover { width: 15vw; }
Comments
Post a Comment