我有一個改變段落字??體大小的輸入。每當我輸入“30px”之類的內容時,輸入都會更改段落的大小。我希望它能夠在我只輸入我想要的尺寸數字而無需在其后添加“px”時進行更改。
我旁邊還有 2 個按鈕,表示增加或減少值,但我不知道如何讓它們更改值。
顯然,我希望這一切都能正常作業,而無需在數字后面加上“px”,但我似乎無法弄清楚。
任何幫助表示贊賞。
我的代碼:
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" value="20px">
<button id="sizeChanger">Change</button>
<button id="addTen"> 10px</button>
<button id="minusTen">-10px</button>
</th>
</tr>
上面代碼的Javascript
var changeTextSize = function () {
console.log('in changeTextSize');
var newTextSize = document.getElementById("textSizeInput").value;
document.getElementById("showText").style.fontSize = newTextSize;
}
document.getElementById('sizeChanger').onclick = changeTextSize;
document.getElementById('textSizeInput').onchange = changeTextSize;
uj5u.com熱心網友回復:
您可以click為每個按鈕添加一個事件偵聽器,這些按鈕呼叫一個函式并將輸入的值增加一定數量。
要增加值,請獲取輸入的值,拆分為"px",獲取第一項,將其增加值,連接"px"然后分配回輸入的 value 屬性:
var input = document.getElementById("textSizeInput")
var changeTextSize = function() {
console.log('in changeTextSize');
var newTextSize = input.value;
document.getElementById("showText").style.fontSize = newTextSize;
}
document.getElementById('sizeChanger').onclick = changeTextSize;
document.getElementById('textSizeInput').onchange = changeTextSize;
function increment(value){
let currentValue = input.value.split("px")[0]
input.value = currentValue value "px";
}
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" value="20px">
<button id="sizeChanger">Change</button>
<button id="addTen" onclick="increment(10)"> 10px</button>
<button id="minusTen" onclick="increment(-10)">-10px</button>
</th>
</tr>
<p id="showText">Hello World!</p>
uj5u.com熱心網友回復:
沒有任何資料驗證或邊界檢查:
function increment() {
const input = document.getElementById("textSizeInput");
input.value = Number(input.value) 10;
}
function decrement() {
const input = document.getElementById("textSizeInput");
input.value = Number(input.value) - 10;
}
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" size="5" value="20"> px
<button id="addTen" onclick="increment()"> 10px</button>
<button id="minusTen" onclick="decrement()">-10px</button>
</th>
</tr>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/330671.html
標籤:javascript html 按钮 输入 增量
下一篇:如何阻止React按鈕同步渲染?
