Html 使用css将鼠标悬停在其他两个元素上时为元素设置动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17200141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:15:56  来源:igfitidea点击:

Animating an element when hovering on two other element using css

htmlcsscss-transitions

提问by It worked yesterday.

i am trying to animate a div when hovering on another div. Ihave following code

我试图在悬停在另一个 div 上时为 div 设置动画。我有以下代码

html

html

<div>
</div>
<div class="content">
</div>

css

css

div {
    height: 100px;
    width: 100px;
    background: red; 
        transition: all 0.4s ease-in-out;
}
.content {
    height: 20px;
    width: 20px;
    background: green;
    display: none;

}
div:hover + .content{
    display: block;
    margin-top: -100px;
    margin-left: 50px;
}

What i am trying to do is, i need to animate .content to margin-top: -100px and margin-left: 50px; from its default position, when the user is hover on one of these elements. But atm with this code it only works when the user hover on the .content and it animate the other way. (from margin-top: -100px and margin-left: 50px; to default position). Please excuse my english

我想要做的是,我需要将 .content 动画到 margin-top: -100px 和 margin-left: 50px; 当用户将鼠标悬停在这些元素之一上时,从其默认位置开始。但是使用此代码的 atm 仅在用户将鼠标悬停在 .content 上时才有效,并以另一种方式进行动画处理。(从 margin-top: -100px 和 margin-left: 50px; 到默认位置)。请原谅我的英语

jsfiddle-> http://jsfiddle.net/fTAUk/1/

jsfiddle-> http://jsfiddle.net/fTAUk/1/

回答by Derek Story

You need to wrap the content in the div and use a child selector. Note I gave the larger div an id as well. Here is the css:

您需要将内容包装在 div 中并使用子选择器。注意我也给了较大的 div 一个 id。这是CSS:

JS Fiddle

JS小提琴

#box {
    height: 100px;
    width: 100px;
    background: red;
    position: absolute;
    transition: all 0.4s ease-in-out;
}
#content {
    width: 20px;
    background: green;
    height: 0;
    transition: all 0.4s ease-in-out;
    position: margin-top: -100px;
    margin-left: 50px;
    -webkit-transition: all .8s ease;
    -moz-transition: all .8s ease;
    -ms-transition: all .8s ease;
    -o-transition: all .8s ease;
    transition: all .8s ease;
}
#box:hover > #content {
    height: 20px;
}