20

为了在一个元素中使用鼠标,我们使用:hoverCSS 属性。鼠标离开元素怎么样?

我在元素上添加了一个过渡效果来改变颜色。悬停效果很好,但是我应该使用什么 CSS 属性让鼠标移出来应用效果?我正在寻找 CSS 解决方案,而不是 JavaScript 或 JQuery 解决方案。

4

4 回答 4

58

我认为这是最好的解决方案。

CSS onomouseout:

div:not( :hover ){ ... }

CSS 鼠标悬停:

div:hover{ ... }

更好,因为如果您只需要在mouseout 上设置一些样式并尝试以这种方式执行此操作

div { ... }

您将设置您的样式和 onmouseover 了。

于 2015-07-01T11:03:26.270 回答
23

CSS 本身不支持mouseinormouseout选择器。

选择:hover器将在鼠标悬停时应用于元素,在鼠标进入时添加样式,在鼠标离开时删除样式。

最接近的方法是定义您将放置在mouseout默认(非悬停)样式中的样式。当您将鼠标悬停在元素上时,其中的样式hover将生效,模拟 a mousein,当您将鼠标移出元素时,默认样式将再次生效,模拟mouseout.

这是一个示例,取自此处

div {
    background: #2e9ec7;
    color: #fff;
    margin: 0 auto;
    padding: 100px 0; 
    -webkit-transition: -webkit-border-radius 0.5s ease-in;
    -moz-transition: -moz-border-radius 0.5s ease-in;
    -o-transition: border-radius 0.5s ease-in;
    -ms-transition: border-radius 0.5s ease-in;
    transition: border-radius 0.5s ease-in;
    text-align: center;
    width: 200px;
}


div:hover {
    background: #2fa832;
    -webkit-border-radius: 100px;
    -moz-border-radius: 100px;
    border-radius: 100px;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
    -webkit-transform: rotate(720deg);
    -moz-transform: rotate(720deg);
    -o-transform: rotate(720deg);
    -ms-transform: rotate(720deg);
    transform: rotate(720deg);
}

transition为样式定义的s 将在鼠标进入(并被应用)div:hover时生效。hover样式的transitions将在鼠标离开(并被移除)div时生效。hover这导致mouseinmouseout转换不同。

于 2013-08-28T16:31:52.377 回答
7

我想我已经找到了解决方案。

.class :hover {
    /*add your animation of mouse enter*/
}

.class {
    /*
    no need for not(hover) or something else. 
    Just write your animation here and it will work when mouse out
    */
}

去尝试一下... :)

于 2016-05-11T12:31:37.737 回答
2

You only need the :hover , when you mouse out of the element, it'll return to it's default non-:hover state, like this:

.class { color: black; } 
.class:hover { color: red; }

when you hover, the color will be red and when you "mouseout", the color will return to black because it no longer matches the :hover selector. This is the default behavior for all browsers, nothing special you need to do here.

于 2013-08-28T16:31:38.103 回答