简体   繁体   中英

How to show CSS transitions only on hover?

I have added a transition onto a div, so that when it is hovered on, the color changes, bit like this example here: http://jsfiddle.net/78LWT/

Here's the HTML code:

<div id="transition"></div>

Here's the CSS code:

#transition {
    background-color: #DA1E1E;
    width: 100px;
    height: 100px;
    transition: .5s background-color;
    -webkit-transition: .5s background-color;
    -moz-transition: .5s background-color;
}
#transition:hover {
    background-color: #ADE1E1;
}

But here's the problem: http://jsfiddle.net/E295T/ (same CSS code as before), with this HTML code:

<div id="transition"></div><br />
<button onclick="recolortransitiondiv();">Recolor that div!</button>

And this JavaScript/jQuery code:

function recolortransitiondiv() {
    $("#transition").css("background-color", "#1EDA1E");
}

And that's where my problem comes in. When the color is to be changed by any method other than hovering over it (for example, when the div is active, or maybe when the div's properties are changed with JavaScript/jQuery), I don't want the transition to show, but I want the transition to show when I hover over the div.

Is there any way I can solve this problem? I am willing to use jQuery, plain JavaScript, CSS and HTML.

As you commented, if you want to prevent transition while the background-color is changed using button , the way to do is, to use transition on the :hover block

#transition:hover {
    background-color: #ADE1E1;
    transition: .5s background-color;
    -webkit-transition: .5s background-color;
    -moz-transition: .5s background-color;
}

Demo 2 ( background-color won't change though, read ahead)

Note: Anyways you will need the below solution as well, else your background-color won't be changed

Demo 3 (If you care to :hover even after changing the background-color using jQuery)


That is because jQuery adds inline CSS which has highest preference/most specific and hence, :hover background-color won't be respected, you will have to use !important in this case

Demo

#transition:hover {
    background-color: #ADE1E1 !important;
}

Or else, it would be better, if you prefer adding and removing class using jQuery, instead of using .css() method, than you won't require !important as well.

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