首页 > 解决方案 > 如何使跨度出现在另一个跨度下?

问题描述

我试图为我的网站制作动画介绍,但我不知道如何让动画背景出现在文本跨度之前。

我已经尝试过使用z-index,但似乎没有用。

#frontcolor {
  z-index: 2;
  animation: revBackDrop 1s linear 0s;
  animation-fill-mode: forwards;
  display: block;
  background-color: #eceff4;
  height: 100%;
  width: auto;
  box-shadow: inset 3px 3px 5px 6px #ccc;
}

#titletext {
  z-index: 1;
  position: absolute;
  display: block;
  top: 8px;
  left: 50%;
  margin-left: -65px;
  color: red;
  font-size: 48px;
  font-family: 'Oswald', sans-serif;
}
<span id="frontcolor"></span>
<span id="titletext">Autorzy</span>

标签: htmlcss

解决方案


正如@Mike 上面指出的那样,一个元素需要 aposition才能z-index有效。

请参见下面的示例。#frontcolor已分配position: relative,因此您现在可以调整它z-index。单击按钮将更改其z-index以使其显示在前面或后面#titletext

添加该position属性应该允许您对网站上的动画执行所需的操作。

var btn = document.getElementById('switchBtn');
var span1 = document.getElementById('frontcolor');

btn.addEventListener('click', function() {
  // on click, switch which span is in front
  if (span1.style.zIndex == 0) {
    span1.style.zIndex = 2;
  } else {
    span1.style.zIndex = 0;
  }
});
#frontcolor {
  position: relative;  /* added to apply z-index */
  z-index: 0;
  animation: revBackDrop 1s linear 0s;
  animation-fill-mode: forwards;
  display: block;
  background-color: #eceff4;
  height: 100%;
  width: auto;
  box-shadow: inset 3px 3px 5px 6px #ccc;
}

#titletext {
  z-index: 1;
  position: absolute;  /* added to apply z-index */
  display: block;
  top: 8px;
  left: 50%;
  margin-left: -65px;
  color: red;
  font-size: 48px;
  font-family: 'Oswald', sans-serif;
}
<span id="frontcolor">frontcolor span</span>
<span id="titletext">titletext span</span>

<br /><br />
<button id="switchBtn">Switch</button>


推荐阅读