在原生 JavaScript 中,你可以通过设置 `input` 元素的 `placeholder` 属性来为其添加占位符文本。以下是具体实现的代码示例: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>设置 input 占位符</title> </head> <body> <!-- 创建一个 input 元素 --> <input type="text" id="myInput"> <script> // 通过 ID 获取 input 元素 const inputElement = document.getElementById('myInput'); // 设置 placeholder 属性的值 inputElement.placeholder = '请输入内容'; </script> </body> </html> ``` 在上述代码中,首先在 HTML 里创建了一个 `input` 元素并赋予其 `id` 为 `myInput`。然后在 JavaScript 代码中,使用 `document.getElementById` 方法根据 `id` 获取到该 `input` 元素,最后将 `placeholder` 属性的值设置为 `'请输入内容'`。 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. 确保在设置 `placeholder` 属性之前,`input` 元素已经被正确加载到 DOM 中,否则可能会导致获取元素失败。 2. 不同浏览器对 `placeholder` 样式的支持和渲染可能存在差异,若需要自定义样式,要进行充分的兼容性测试。 3. 对于动态创建的 `input` 元素,要在元素创建完成后再去设置 `placeholder` 属性,避免出现设置无效的情况。 [2025-08-21 18:43:44 | AI写代码神器 | 385点数解答]