有很多在选中复选框时为所有标签着色的示例。我需要为带有“for”属性的单个标签着色
我正在努力:
input[type="checkbox"]:checked~label[for=Sign_me_up_for_the_newsletter_and_periodic_alerts] {
background: green !important;
}
<div class="pull-right">
<label for="Sign_me_up_for_the_newsletter_and_periodic_alerts">Sign me up for the newsletter and periodic alerts</label>
<input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
<br>
<label class="text-danger" for="I_Agree_to_the_Terms_of_Agreement">I agree to the terms of agreement</label>
<input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>
当我选中复选框时,没有任何反应
一种可能的解决方案是在选中复选框时使用 JavaScript 将类添加到标签。具体方法如下:
<style>
/* Define the style for the highlighted label */
.highlight-label {
color: green !important;
}
</style>
<div class="pull-right">
<!-- Use a unique ID for the label -->
<label for="newsletter_optin" id="newsletter_label">Sign me up for the newsletter and periodic alerts</label>
<input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
<br>
<label class="text-danger" for="I_Agree_to_the_Terms_of_Agreement">I agree to the terms of agreement</label>
<input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>
<script>
// Get the checkbox and label elements
const checkbox = document.getElementById('newsletter_optin');
const label = document.getElementById('newsletter_label');
// Add event listener to the checkbox
checkbox.addEventListener('change', function() {
// If checkbox is checked, add the 'highlight-label' class to the label; otherwise, remove the class
if (this.checked) {
label.classList.add('highlight-label');
} else {
label.classList.remove('highlight-label');
}
});
</script>