更改CSS中悬停div的背景

时间:2017-05-18 13:57:28

标签: html css

我有一些div,当你将它们悬停时,我想改变背景。

首先我的背景是隐藏的,当你悬停这样的事情时,会发生背景中的文字,如下所示:

enter image description here

这是我到目前为止所能做的,但我遇到了css或html结构的问题:

.first-background {
    height: 100vh;
    width: 100vw;
    background-color: black;
    visibility: hidden;
    opacity: 0;
    position: absolute;
}

h1 {
    font-size: 10em;
    color: white;
}

.first {
    height: 20px;
    width: 20px;
    background-color: blue;
}

.first:hover .first-background {
    visibility: visible;
    opacity: 1;
}
<div class="first-background">
        <h1>FIRST</h1>
    </div>


    <div class="container">
        <div class="col-md-12">
            <div class="section col-md-4 col-xs-12">
                <div class="first">
                    <div class="content">
                    </div>
                </div>
            </div>
        </div>
    </div>

2 个答案:

答案 0 :(得分:2)

要做类似的事情,你需要在你的html标签中使用onmouseover。我做了一个简单的例子,试图告诉你如何做到这一点。

function changebg(){
  document.getElementById("cont").style.background = "url('https://image.freepik.com/free-vector/purple-background-of-colorful-triangles_23-2147616335.jpg')";
}

function resetbg(){
  document.getElementById("cont").style.background = "";
}
.container {
  width: 200px;
  height: 200px;
}

.square {
  width: 50px;
  height: 50px;
  background-color: blue;
}
<div class="container" id="cont">
  <div class="square" onmouseover="changebg()" onmouseout="resetbg()">
  </div>
</div>

答案 1 :(得分:1)

您可以使用+(或~

定位下一个同级元素

*{margin:0;box-sizing:border-box;}

/* some common styles */
#wrapper{
  position: relative;
}
#box{
  position: absolute;
  z-index:1; /* overlap #content */
  top: 20px;
  left: 20px;
  width: 20px;
  height: 20px;
  background: #0bf;
  cursor: pointer;
}
#content{
  background: #ddd;
  color: #fff;
  padding: 70px;
  /* we'll transition opacity */
  opacity: 0;
  transition: 0.3s;
}

/* the magic here */
#box:hover + #content{
  opacity: 1;
}
<div id="wrapper">

  <div id="box"></div>
  
  <div id="content">
    <h1>SECOND THIS!</h1>
  </div>
  
</div>