我正在尝试创建加号和减号按钮以与滑块一起使用(输入类型=“范围”)。 但是它没有像我期望的那样工作。我创造了一个小提琴:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
var buttonMinusRef = document.getElementById("buttonMinus");
var buttonPlusRef = document.getElementById("buttonPlus");
var brushSizeRef = document.getElementById("brushSize");
buttonMinusRef.addEventListener("click", incrementBrushSize, false);
buttonPlusRef.addEventListener("click", incrementBrushSize, false);
function incrementBrushSize() {
if (this.id === "buttonPlus") {
/* Plus Button was clicked. */
if (brushSizeRef.value < brushSizeRef.max) {
brushSizeRef.value++;
drawSize = brushSizeRef.value;
console.log("it works");
} else {
console.log("it doesn't work");
}
} else {
/* Minus Button was clicked. */
}
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="myScript.js"></script>
<title>Test</title>
</head>
<body>
<p>Brush size: <span id="currentSize"></span>
</p>
<button id="buttonMinus">-</button>
<input type="range" id="brushSize" min="1" max="140" value="20" />
<button id="buttonPlus">+</button>
<br />
</body>
</html>
我对此代码的想法是:用户点击加号或减号按钮。如果单击加号按钮,则滑块值增加1(减去1减去。) 如果当前.value小于.max(而减号按钮则相反),我只希望加号按钮执行任何操作。 我想使用.min,.max和.value来避免将值硬编码到比较中。
会发生什么:当滑块在130到150左右的范围内时,它似乎才有效。我不明白为什么。
答案 0 :(得分:-1)
更改:
if (brushSizeRef.value < brushSizeRef.max) {
致:
if (brushSizeRef.value < parseInt(brushSizeRef.max)) {
最终代码:
<html>
<head>
</head>
<body>
<p>Brush size: <span id="currentSize"></span>
</p>
<button id="buttonMinus">-</button>
<input type="range" id="brushSize" min="1" max="140" value="20" />
<button id="buttonPlus">+</button>
<br />
<script>
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
var buttonMinusRef = document.getElementById("buttonMinus");
var buttonPlusRef = document.getElementById("buttonPlus");
var brushSizeRef = document.getElementById("brushSize");
buttonMinusRef.addEventListener("click", incrementBrushSize, false);
buttonPlusRef.addEventListener("click", incrementBrushSize, false);
function incrementBrushSize() {
if (this.id == "buttonPlus") {
/* Plus Button was clicked. */
if (brushSizeRef.value < parseInt(brushSizeRef.max)) {
brushSizeRef.value++;
drawSize = brushSizeRef.value;
console.log("it works");
} else {
console.log("it doesn't work");
}
} else {
/* Minus Button was clicked. */
}
}
}
</script>
</body>
</html>
答案 1 :(得分:-1)
parseInt函数(brushSizeRef.value)。 brush.min,brush.max,brush.value的类型是字符串,这是它无法工作的原因。