你能告訴我為什么這個簡單的代碼不起作用嗎?我想更改第一個滑塊,第二個滑塊會自動更改。
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canva</title>
</head>
<body >
<input type="range" name="n1" id="id1" value="5" step="2" min="1" max="100" oninput="change()" onchange="change()" />
</br>
<input type="range" name="n2" id="id2" value="2" step="2" min="1" max="100" />
<input type="number" name="n3" id="id3" />
<script>
function change(){
window.document.getElementById('id2').value = 10;
window.document.getElementById('id3').value = 10;
}
</script>
</body>
</html>
uj5u.com熱心網友回復:
每次輸入滑塊更改時都會觸發該change函式。您剛剛硬編碼了輸出滑塊應設定的值。您可以通過將輸出滑塊移動到 10 以外的某個數字來檢查這一點,然后再次移動輸入滑塊。輸出滑塊將回傳到 10。
看起來您希望輸出滑塊的值與輸入滑塊的值匹配。這是一個示例。
呼叫該change函式時,輸出滑塊的值設定為輸入滑塊的當前值。
const sourceSlider = document.getElementById('id1');
const targetSlider = document.getElementById('id2');
const targetInput = document.getElementById('id3');
function change() {
const sourceValue = sourceSlider.value;
targetSlider.value = sourceValue;
targetInput.value = sourceValue;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canva</title>
</head>
<body >
<input type="range" name="n1" id="id1" value="5" step="2" min="1" max="100" oninput="change()" onchange="change()" />
</br>
<input type="range" name="n2" id="id2" value="2" step="2" min="1" max="100" />
<input type="number" name="n3" id="id3" />
<!--<script>
function change(){
window.document.getElementById('id2').value = 10;
window.document.getElementById('id3').value = 10;
}
</script>-->
</body>
</html>
uj5u.com熱心網友回復:
您在更改事件上設定了一個固定值,要獲得一個動態值,您可以從傳遞給事件偵聽器回呼的物件中10讀取值:eventevent.target.value
id1.oninput = e => id2.value = e.target.value;
id3.oninput = e =>
id1.value = id2.value = e.target.value
<input type="range" name="n1" id="id1" value="5" step="2" min="1" max="100" />
</br>
<input type="range" name="n2" id="id2" value="2" step="2" min="1" max="100" />
<input type="number" name="n3" id="id3" />
uj5u.com熱心網友回復:
您的問題在于您使用該change()功能的方式。每次更新時都將其重置為默認值 10,而不是id1.
<!-- ... -->
<script>
// you don't need to say window.document.something
// just say document.something
function change() {
const targetVal = document.getElementById('id1').value;
// sets the value of `id2` and `id3`
document.getElementById('id2').value = targetVal;
document.getElementById('id3').value = targetVal;
}
</script>
<!-- ... -->
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463500.html
標籤:javascript html 范围 滑块
上一篇:在React中正確使用自定義鉤子
下一篇:復選框狀態未在現場更新
