有人能解釋一下為什么我選中自定義復選框時沒有出現勾號,并幫助我解決這個問題嗎?我試圖復制W3Schools的例子,下面是我的代碼:
.bottom {
display: flex;
justify-content: space-between;
width: 300px;
}
.left {
display: flex;
flex-direction: row;
position: relative;
}
/* Hide the actual checkbox */
input[type=checkbox] {
opacity: 0;
margin-right: 4px;
}
/* Create a custom checkbox*/
.checkbox::before {
content: "";
border: none;
border-radius: 2px;
height: 16px;
width: 16px;
position: absolute;
background-color: #737373;
}
.checkbox::after {
content: "";
border: 3px solid;
border-top: 0;
border-left: 0;
width: 4px;
height: 9px;
position: absolute;
top: 1px;
left: 5px;
transform: rotate(45deg);
opacity: 0;
transition: opacity 10ms;
}
.checkbox input:checked ~ .checkbox::after {
opacity: 1;
}
<div class="bottom">
<div class="left">
<div class="checkbox" style="margin-right: 3px;">
<input type="checkbox">
</div>
<span>Remember me</span>
</div>
<span>Need help?</span>
</div>
您在css的最后一個塊中遇到了問題,就在這里:
.checkbox input:checked ~ .checkbox::after {
opacity: 1;
}
解釋:
您正在使用優先選擇器通過類名復選框選擇元素。上面的css塊意味著:“使用類搜索元素”復選框,并在其中搜索選中的輸入元素:選中,然后“使用類搜索元素”復選框,該復選框在選中的輸入設置為選中后可用,或者換句話說,“使用類搜索元素”復選框前面有input t:checked元素,但在html中,輸入標記后沒有元素,因此它不起作用。此外:after和:before選擇器與實際輸入復選框重疊,因此您無法點擊它。這可以通過將兩個選擇器的z索引設置為-1來解決。
更正后的代碼片段如下:
<div class="bottom">
<div class="left">
<div class="checkbox" style="margin-right: 3px;">
<input type="checkbox">
<div class='customcheckbox'></div>
</div>
<span>Remember me</span>
</div>
<span>Need help?</span>
</div>
.bottom {
display: flex;
justify-content: space-between;
width: 300px;
}
.left {
display: flex;
flex-direction: row;
position: relative;
}
/* Hide the actual checkbox */
input[type=checkbox] {
margin:0;
width:16px;
height:16px;
opacity:0;
cursor:pointer;
}
/* Create a custom checkbox*/
.customcheckbox::before {
content: "";
border: none;
border-radius: 2px;
height: 16px;
width: 16px;
position: absolute;
top:0;
left:0;
z-index:-1;
background-color: #737373;
}
.customcheckbox::after {
content: "";
border: 3px solid;
border-top: 0;
border-left: 0;
width: 4px;
height: 9px;
position: absolute;
top: 1px;
left: 5px;
transform: rotate(45deg);
opacity: 0;
z-index:-1;
transition: opacity 10ms;
}
.checkbox input:checked ~ .customcheckbox::after {
opacity: 1;
}
我希望我的解釋是清楚的,并且解決方案也在你這邊起作用。干杯!
上一篇vue 輕量級論壇
下一篇vue 輸入命令組件