簡體   English   中英

更改CSS中將div懸停的背景

[英]Change background on hovering div in CSS

我有一些div,當您將它們懸停時,我想更改背景。

最初,我的背景是隱藏的,當您將鼠標懸停在背景上時,應該發生這樣的事情,如下所示:

在此處輸入圖片說明

到目前為止,這是我可以做的,但是在使用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> 

為此,您需要在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> 

您可以使用+ (或~ )將Next Sibling元素作為目標。

 *{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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM