如何用 JavaScript 切换文本?
以下为使用 JavaScript 切换文本的代码 −
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .textDiv { font-size: 20px; background-color: rgb(199, 228, 157); width: 100%; padding: 15px; font-weight: bold; } .toggleBtn { padding: 15px; border: none; background-color: rgb(106, 41, 153); color: white; font-size: 18px; } </style> </head> <body> <h1>Toggle Text example</h1> <button class="toggleBtn">Click Me</button> <h2>Click on the above button to toggle below text</h2> <div class="textDiv">Old Text</div> <script> document .querySelector(".toggleBtn") .addEventListener("click", toggleText); function toggleText() { var x = document.querySelector(".textDiv"); if (x.innerHTML === "Old Text") { x.innerHTML = "New Text"; } else { x.innerHTML = "Old Text"; } } </script> </body> </html>
输出
上述代码将生成以下输出 −
点击“点击我”按钮后 −
广告