在 JavaScript 中透過程式設計方式為 HTML 輸入數字型別建立加減按鈕


我們將建立兩個按鈕,一個用於增加,另一個用於減少 −

  • 點選加號 (+) 時,使用者將能夠增加輸入數字型別的數字

  • 點選減號 (-) 時,使用者將能夠減少輸入數字型別的數字

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<input id=demoInput type=number min=100 max=110>
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<script>
   function increment() {
      document.getElementById('demoInput').stepUp();
   }
   function decrement() {
      document.getElementById('demoInput').stepDown();
   }
</script>
</body>
</html>

要執行以上程式,請儲存檔名為“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用即時伺服器開啟”選項。

輸出

這將產生以下輸出 −

如果單擊按鈕加號 (+),它會增加 1。單擊減號 (-) 時,會減去 1。

此處,我將使用加號按鈕。

這將產生以下輸出 −

更新日期: 2020 年 9 月 12 日

15 千次以上瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.