利用checked實現收藏按鈕紅心的顯示與隱藏
阿新 • • 發佈:2020-12-09
實現原理:利用checked 選擇器和兄弟選擇器,通過複選框的複選與取消複選,達到收藏紅心的顯示與隱藏效果
預設複選框選中時的狀態
複選框被取消複選的狀態
實現程式碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Document</title>
<link rel="stylesheet" href="http://at.alicdn.com/t/font_2226582_dki77h4juap.css">
<style>
/* 設定一個居中的盒子 */
.box {
margin: 40px auto;
width: 200px;
height: 200px;
}
/* 設定一個盒子放收藏按鈕 */
.font {
float: right;
margin-right: 20px;
width: 86px;
height: 62px;
font-size: 40px;
text-align: center;
}
/* 設定一個放字型圖示及複選框的盒子 */
.heart-box {
position: relative;
width : 86px;
height: 62px;
}
/* 設定字型圖示大小 */
i,
.iconfont {
font-size: 60px;
color: red;
}
/* 定位複選框位置,和其他兩個心重疊,並設定透明度為0,提高層級 */
input {
position: absolute;
left: -17px;
top: -3px;
width: 100%;
height: 100%;
border-radius: 50%;
opacity: 0;
z-index: 2;
}
/* 選中複選框的兄弟元素,當複選框狀態為複選時,使它隱藏 */
input:checked+.icon {
display: none;
}
/* 定位字型圖示 使它和複選框與另一個字型圖示重疊 */
.icon {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<!-- 設定一個居中的盒子 -->
<div class="box">
<!-- 設定一個放收藏兩字的盒子 -->
<div class="font">收藏</div>
<!-- 設定一個放字型圖示及複選框的盒子 -->
<div class="heart-box">
<!-- 設定一個複選框,預設狀態被複選 -->
<input type="checkbox" checked>
<!-- 字型圖示實心 -->
<i class="iconfont icon-shoucangshixin1 icon"></i>
<!-- 字型圖示空心-->
<i class="iconfont icon-shoucang1"></i>
</div>
</div>
</body>
</html>