Home > Article > Web Front-end > Using JavaScript functions to implement user interface interaction
Using JavaScript functions to implement user interface interaction requires specific code examples
Javascript is a powerful scripting language that can be used in many aspects of web development. Among them, what beginners are most concerned about is how to use JavaScript functions to realize user interface interaction.
The following are specific code examples for JavaScript functions to implement interaction in some common situations:
1. Click the button and a prompt box will pop up:
<button onclick="alert('您点击了按钮')">点击我</button>
<script> function changeColor() { document.getElementById("text").style.color = "red"; } </script> <p id="text" onmouseover="changeColor()">我的颜色将在鼠标移入时变为红色</p>
<form> <input type="text" id="age" placeholder="请输入您的年龄"> <button onclick="checkAge()">提交</button> </form> <script> function checkAge() { var age = document.getElementById("age").value; if (isNaN(age)) { alert("请输入数字!"); } else if (age < 18) { alert("未满18岁!"); } else { alert("年龄合法!"); } } </script>
<a href="#contact">联系我们</a> // 具体实现锚点跳转的代码需要写在页面底部 <a name="contact"></a>
<div class="menu"> <a href="#" onclick="showContent('home')">首页</a> <a href="#" onclick="showContent('about')">关于我们</a> <a href="#" onclick="showContent('product')">产品介绍</a> <a href="#" onclick="showContent('contact')">联系我们</a> </div> <div id="home" class="content">这是首页</div> <div id="about" class="content">这是关于我们</div> <div id="product" class="content">这是产品介绍</div> <div id="contact" class="content">这是联系我们</div> <script> function showContent(id) { var contents = document.getElementsByClassName("content"); for (var i = 0; i < contents.length; i++) { contents[i].style.display = "none"; } document.getElementById(id).style.display = "block"; } </script>
The above are just some basic examples. JavaScript is widely used and can be more complex. and rich interactive effects. I hope readers can quickly master how to use JavaScript functions to implement user interface interaction through these code examples.
The above is the detailed content of Using JavaScript functions to implement user interface interaction. For more information, please follow other related articles on the PHP Chinese website!