使用 JavaScript 在 HTML 中將預設搜尋文字新增到搜尋框?


你可以使用佔位符的概念。以下是 JavaScript 程式碼 −

示例

 線上演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=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>
</head>
<body>
<input type="text" id="textSearch" placeholder="Search the value" />
<script>
   var yourText= "John";
   var textBoxSearch = document.getElementById("textSearch");
   textBoxSearch.value = yourText;
   textBoxSearch.onfocus = function() {
      if (this.value == yourText) {
         this.value = '';
      }
   }
</script>
</body>
</html>

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

輸出

當您單擊搜尋框時,將顯示佔位符值。快照如下 −


更新日期: 16-Jul-2020

435 次瀏覽

開創您的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.