悬停时向上移动 HTML 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33271928/
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 18:23:45  来源:igfitidea点击:

Move HTML element upwards on hover

htmlcsscss-animations

提问by Manoj Kumar

I am trying to move an HTML up about 10px whenever a user hovers their mouse over it. I did some research on w3schools but I could not find any information that helped me. Most of their animation examples were using keyframes and I'm pretty sure that's not what I need because I'm trying to trigger an animation when somebody hovers over the element. I could be wrong though and that's why I'm posting here.

每当用户将鼠标悬停在 HTML 上时,我都会尝试将其向上移动约 10 像素。我对 w3schools 做了一些研究,但找不到任何对我有帮助的信息。他们的大多数动画示例都使用了关键帧,我很确定这不是我需要的,因为我试图在有人悬停在元素上时触发动画。不过我可能是错的,这就是我在这里发帖的原因。

Here's the element I'm trying to move:

这是我要移动的元素:

<div id="arrow">
  <a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>

For my CSS:

对于我的 CSS:

#arrow {
  padding-top: 310px;
  color: #5C6B7E;
  position: relative;
  /* some kind of animation property here? */
}

#arrow:hover {
  /* new properties once user hovers */
}

I'm not sure what I need to add to make the element animate up, the examples on w3schools weren't of much help. If anybody could point me in the right direction I would be extremely appreciative. Thank you Stack Overflow.

我不确定我需要添加什么来使元素具有动画效果,w3schools 上的示例没有太大帮助。如果有人能指出我正确的方向,我将不胜感激。谢谢堆栈溢出。

回答by Manoj Kumar

You need not use keyframes for this simple animation. Just CSS transition is enough.

您不需要为这个简单的动画使用关键帧。只需 CSS 过渡就足够了。

Set the transitionproperty in the initial state style rules with the duration.

transition使用持续时间在初始状态样式规则中设置属性。

#arrow {
  position: relative;
  top: 0;
  transition: top ease 0.5s;
}
#arrow:hover {
  top: -10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="arrow">
  <a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>