html - 悬停时隐藏/显示切换并在 css 中淡入淡出

标签 html css toggle

我有一个简单的隐藏/显示切换,它在悬停时淡入/淡出文本。唯一的问题是,我不希望它是不可见的(因为它占用了不必要的空间)。但是当我添加显示元素时,淡入淡出功能不再起作用。

#stuff {
  opacity: 0.0;
  -webkit-transition: all 400ms ease-in-out;
  -moz-transition: all 400ms ease-in-out;
  -ms-transition: all 400ms ease-in-out;
  -o-transition: all 400ms ease-in-out;
  transition: all 400ms ease-in-out;
  color: black;
  text-align: center;
  border-style: solid;
  border-width: 1px;
  border-color: #e0e0e0;
  border-radius: 25px;
  width: 200px;
}

#hover {
  width: 150px;
  height: 10px;
  margin-bottom: 15px;
  cursor: pointer;
  float: center;
  font-family: 'Open Sans', FontAwesome;
  font-weight: 600;
}

#hover:hover+#stuff {
  opacity: 1.0;
  display: inline-block;
}

`
<div id="hover">HOVER HERE</div>
<div id="stuff">Revealed text</div>

带有淡入淡出动画,但只是隐藏:jsfiddle

没有淡入淡出动画,但在悬停时出现并且不占用空间jsfiddle

是否可以在文本不可见的情况下保持淡入淡出动画?

最佳答案

您可以使用max-height删除不需要的空间

请参阅下面的代码片段:

#stuff {
  opacity: 0.0;
  -webkit-transition: all 400ms ease-in-out;
  -moz-transition: all 400ms ease-in-out;
  -ms-transition: all 400ms ease-in-out;
  -o-transition: all 400ms ease-in-out;
  transition: all 400ms ease-in-out;
  color: black;
  text-align: center;
  border-style: solid;
  border-width: 1px;
  border-color: #e0e0e0;
  border-radius: 25px;
  width: 200px;
  max-height:0;
}

#hover {
  width: 150px;
  height: 10px;
  margin-bottom: 15px;
  cursor: pointer;
  float: center;
  font-family: 'Open Sans', FontAwesome;
  font-weight: 600;
}

#hover:hover+#stuff {
  opacity: 1.0;
  max-height:100%;
  
}
<div id="hover">HOVER HERE</div>
<div id="stuff">Revealed text</div>

如果你希望它始终不占用空间,你可以使用绝对位置来使其脱离文档的流程

查看代码片段:

#stuff {
  opacity: 0.0;
  -webkit-transition: all 400ms ease-in-out;
  -moz-transition: all 400ms ease-in-out;
  -ms-transition: all 400ms ease-in-out;
  -o-transition: all 400ms ease-in-out;
  transition: all 400ms ease-in-out;
  color: black;
  text-align: center;
  border-style: solid;
  border-width: 1px;
  border-color: #e0e0e0;
  border-radius: 25px;
  width: 200px;
  position:absolute;
}

#hover {
  width: 150px;
  height: 10px;
  margin-bottom: 15px;
  cursor: pointer;
  float: center;
  font-family: 'Open Sans', FontAwesome;
  font-weight: 600;
  
}
.wrapper{
  position:relative;
}
#hover:hover + #stuff {
  opacity: 1.0;   
}
<div class="wrapper">
<div id="hover">HOVER HERE</div>
<div id="stuff">Revealed text</div>
<div>

关于html - 悬停时隐藏/显示切换并在 css 中淡入淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804210/

相关文章:

javascript - 想要显示前三个 div,然后让剩余部分切换

c# - 这是“切换” boolean 值的可接受方法吗?

javascript - 按类排列的元素数组 - TypeError : $. id 不是函数

css - 在移动设备上查看时缺少自定义 CSS 复选框边距

Javascript帮助,切换文本不断跳回到页面顶部

html - 两个 div 与省略号并排 - 最小宽度问题

javascript - webpack导入css文件出错

html - 有没有办法设置选择元素的箭头样式?

javascript - 如何使用 jquery 对所有可点击项目使用一种方法?

php - IF 语句不改变变量的结果