我有一个复选框伪元素,用于替换隐藏的复选框输入,当需要隐藏的复选框时,我想突出显示它。有什么 css 解决方案吗?解决问题的正确方法是什么? https://jsfiddle.net/ht2c9sbd/3/
<form>
<div class="group-input">
<input type="checkbox" id="c_1" required hidden="">
<label for="c_1">I agree with everything.</label>
</div>
<input type="submit" value="submit" id="submit">
</form>
css:
input[type="checkbox"] + label::before {
content: "";
display: inline-block;
height: 30px;
width: 30px;
margin: 0 14px 0 0;
cursor: pointer;
vertical-align: middle;
position: absolute;
left: 0;
top: calc(50% - 15px);
-webkit-transition: background-color 0.25s ease, border-color 0.25s ease;
transition: background-color 0.25s ease, border-color 0.25s ease;
}
input[type="checkbox"] + label::before {
content: "";
display: inline-block;
height: 30px;
width: 30px;
border: 1px solid rgba(20, 61, 139, 0.2);
margin: 0 14px 0 0;
cursor: pointer;
vertical-align: middle;
position: relative;
top: -2px;
}
input[type="checkbox"]:checked + label::before {
background-image: url(https://image.flaticon.com/icons/png/512/447/447147.png);
background-size: 15px;
border: 1px solid rgba(20, 61, 139, 0);
background-color: rgba(20, 61, 139, 0.2);
background-position: center;
background-repeat: no-repeat;
}
这是我可怕的js解决方案:
function checkCheckbox(e) {
if (!e.checked) {
$('head').append('<style id="invalidCheckbox">input[type="checkbox"] + label::before {border: 1px solid #ff3535; box-shadow: 0 0 2px #ff3535;}</style>');
return false;
} else {
let temp = $('head style:last');
while(temp && temp[0].id === "invalidCheckbox"){
temp.remove();
temp = $('head style:last');
}
return true;
}
}
const mycheckbox = document.getElementById('c_1');
document.getElementById("submit").addEventListener('click', function(e){
e.preventDefault();
checkCheckbox(mycheckbox);
});
答案 0 :(得分:1)
脚本:
const mycheckbox = document.getElementById('c_1');
document.getElementById("submit").addEventListener('click', function(e){
e.preventDefault();
if ( mycheckbox.hasAttribute('required') && !mycheckbox.checked ){
mycheckbox.className = "invalid-input"; // <-- add new class
} else {
mycheckbox.className = "";
}
});
样式(您可以根据需要更改样式):
input[type="checkbox"].invalid-input + label::before{
background-color: red;
}
请尝试更新现有DOM元素,而不要在DOM中创建新元素,因为DOM操作速度很慢。
当对元素外观进行了明显更改但不影响其布局的元素外观时,就会发生重新绘制。
创建新的DOM元素对于性能而言更为关键,因为它涉及影响页面一部分布局的更改
答案 1 :(得分:0)
突出显示required
复选框:
在CSS中:
/* Style (any) element with the required attribute: */
:required {
background: red;
}
/* Style input elements with the required attribute: */
input:required {
box-shadow: 1px 1px 10px rgba(200, 0, 0, 0.5);
}
/* Style focused and required element: */
input:required:focus {
border: 2px solid red;
outline: none;
}
/* Style hover and required element: */
input:required:hover {
opacity: 1;
}
在JS中:
// Get the element
var req = document.getElementById("my_checkbox").required;
// Check if required
if(req.hasAttribute('required')) {
// Style it
req.style.background = "red";
}