如何使用脚本禁用/启用HTML中的范围控件



我对html/jquery/javascript很陌生。我有下面的脚本上的一个按钮点击禁用范围控制。如果第二次单击该按钮,我需要重新启用范围控制。那么,如何检查范围控制是禁用还是启用?

$(":button.range").click(function(){
$(this).parent().parent().find("input[type='range']:visible:first").attr("disabled","disabed");
});

您可以这样做:

$(":button.range").click(function(){
let status = $(this).parent().parent().find("input[type='range']:visible:first").prop('disabled');
if(status === true){
$(this).parent().parent().find("input[type='range']:visible:first").prop('disabled',false);
}else{
$(this).parent().parent().find("input[type='range']:visible:first").prop('disabled',true);
}
});  

您可以使用下面的jquery来了解是否禁用了输入范围控制。

if ($(this).parent().parent().find("input[type='range']").prop("disabled") === true) {
//write your code for disabled range control
}

如果您想启用相同的控件,请使用下面这样的jquery。

$(this).parent().parent().find("input[type='range']").prop("disabled", false);

如果你只是想切换它,你可以使用下面的脚本:

$(":button.range").click(function(){
let status = $(this).parent().parent().find("input[type='range']:visible:first").prop('disabled');
$(this).parent().parent().find("input[type='range']:visible:first").prop('disabled', !status);
});  

如果它是true,则它将把它设置为false,反之亦然。

您可以使用toggleAttribute()->https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

My Example使用Vanilla JavaScript,但我认为您也可以将其用于jQuery Example。

$(":button.range").click(function(){
$(this).parent().parent().find("input[type='range']:visible:first").toggleAttribute("disabled");
});

const toggleButton = document.getElementsByClassName('toggle')[0];
const rangeSlider = document.getElementById('start');
const toggleRange = () => {
const status = rangeSlider.toggleAttribute('disabled');
console.log(status);
};
toggleButton.addEventListener('click', toggleRange);
<div>
<input type="range" id="start" name="volume" min="0" max="11">
<label for="volume">Volume</label>
</div>
<button class="toggle">toggle</button>

最新更新