首页 > 解决方案 > 悬停时可以将元素带到另一个兄弟元素吗?[CSS动画]

问题描述

当元素悬停时,我想让元素移动到另一个元素。这些元素是兄弟,因为我希望一个覆盖另一个。

下面的 HTML 和 CSS 给了我不错的结果。但我不想为“width”和“left”使用常量值来为它们设置动画。有没有办法在不使用恒定位置值的情况下将移动元素放置在悬停元素上?

nav .animation {
  position: absolute;
  height: 100%;
  top: 0;
  z-index: 0;
  transition: all .5s ease 0s;
  border-radius: 8px;
}

nav .start-home,
a:nth-child(1):hover~.animation {
  width: 105px;
  left: 0;
  background-color: #1abc9c;
}

nav .start-blog,
a:nth-child(2):hover~.animation {
  width: 105px;
  left: 105px;
  background-color: #e74c3c;
}

nav .start-projects,
a:nth-child(3):hover~.animation {
  width: 135px;
  left: 210px;
  background-color: #3498db;
}

nav .start-about,
a:nth-child(4):hover~.animation {
  width: 115px;
  left: 345px;
  background-color: #9b59b6;
}

nav .start-contact,
a:nth-child(5):hover~.animation {
  width: 130px;
  left: 460px;
  background-color: #e67e22;
}


nav {
  margin: 27px auto 0;
  position: relative;
  display: table;
  height: 50px;
  background-color: #34495e;
  border-radius: 8px;
  font-size: 0;
  white-space: nowrap;
}
nav a {
  line-height: 50px;
  padding: 2px 30px;
  height: 100%;
  font-size: 15px;
  display: inline-block;
  position: relative;
  z-index: 1;
  text-decoration: none;
  text-transform: uppercase;
  text-align: center;
  color: white;
  cursor: pointer;
}
<nav>
  <a href="#">Home</a>
  <a href="#">Blog</a>
  <a href="#">Projects</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
  <div class="animation start-home"></div>
</nav>

标签: javascripthtmlcssanimation

解决方案


我找不到仅使用 CSS 的方法,所以我使用了 JavaScript 并修改了元素的样式。这是我不想做的事情。如果您只知道如何使用 CSS,请告诉我。


推荐阅读