一、概述
hover偽類:在鼠標移到元素上時向此元素添加特殊的樣式。比較普通的就是一個url,當你鼠標放上去后,會變顏色。
在現實的應用場景也非常之多。最常見的是網站的懸浮導航,當鼠標放到導航條上時,會出現顏色變化或者元素自動伸出菜單欄。
實例1:鼠標hover時,將內容框起來
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.ele:hover {
border:1px solid red;
}
.ele { #去掉邊框閃爍問題。(因為邊框1像素會導致閃爍,所以先用1px透明色占住位置,hover時再讓其變紅,就不會覺得有閃爍了)
border:1px solid transparent;
}
</style>
</head>
<body>
<div class="ele">
<div>222</div>
<div class="ele-item">111</div>
</div>
</body>
</html>
原始效果:
鼠標懸停后:
實例2:尾品會vdangdang.com首頁最下面有這樣的圖片
原始網頁:
鼠標懸停后效果:
其實這個主要就是用hover制作而成。下面說一下具體實現:
實現思路:
1、新建一個div1
2、新建一個div2,把底部圖片放入div2
3、再新建一個div3,懸浮內容放入div3
HTML代碼:
<div class="touch"> <div><img src="3.png"></div> <div class="content"> <p><h5>品牌故事</h5></p> <p><h6>我們的源泉不是時尚,不是潮流,而是由心而發的喜愛,將精致華麗的藝術融入東方式的低調,都只為了一個人而存在。</h6></p> <input class="inpt" type="text" name="tel" id="tel"/> <button class="btn">開售提醒</button> </div> </div>
CSS代碼:
1、定義div1高度和寬度,class為touch,overflow設置為hidden,圖片超過定義的高度和寬度會隱藏。
.touch {
height:200px;
width:400px;
overflow:hidden;
position:relative;
}
2、div2為content,內容必須填滿div1,所以設置上下左右都為0.且設置字體大小、顏色、對齊方式。
首先設置div2為不可見,即在鼠標hover之前內容默認是隱藏的,當鼠標懸浮后,再放出來。
.touch .content {
top:0;
left:0;
right:0;
bottom:0;
position:absolute;
font-size:20px;
background-color:black;
color:white;
text-align:center;
visibility:hidden;
}
3、設置鼠標懸浮時樣式。內容放出來,且設置背景圖片透明度為0.5,可以被看到。
.touch:hover .content{
visibility:visible;
border:4px solid red;
background-color:rgba(0,0,0,0.5)
}
4、最后設置input框和button
.touch .content .btn{
background-color:#e83375;
color:white;
cursor: pointer;
border: none;
width: 70px;
height: 22px;
}
.touch .content .inpt{
height: 18px;
border: none
line-height: 18px;
font-size: 12px;
}
整體html代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .touch { height:200px; width:400px; overflow:hidden; position:relative; } .touch .content { top:0; left:0; right:0; bottom:0; position:absolute; font-size:20px; background-color:black; color:white; text-align:center; visibility:hidden; } .touch:hover .content{ visibility:visible; border:4px solid red; background-color:rgba(0,0,0,0.5) } .touch .content .btn{ background-color:#e83375; color:white; cursor: pointer; border: none; width: 70px; height: 22px; } .touch .content .inpt{ height: 18px; border: none line-height: 18px; font-size: 12px; } </style> </head> <body> <div class="touch"> <div><img src="3.png"></div> <div class="content"> <p><h5>品牌故事</h5></p> <p><h6>我們的源泉不是時尚,不是潮流,而是由心而發的喜愛,將精致華麗的藝術融入東方式的低調,都只為了一個人而存在。 </h6></p> <input class="inpt" type="text" name="tel" value="請輸入手機號碼或郵箱地址" id="tel"/> <button class="btn">開售提醒</button> </div> </div> </body> </html>
關鍵知識點:
1、最外面的div設置成relative,把content設置absolute,然后top、bottom、left、right設置均為0,即把content鋪滿div;
2、visibility:hidden;默認隱藏最上面的內容;
3、visibility:visible和background-color:rgba(0,0,0,0.5),hover時放出內容,並且設置背景透明度,可以看到背景圖片;