[前端开发] 常见的 HTML、CSS、JavaScript 事件代码示例

  • 概念指路 常见的 HTML CSS JavaScript 事件

常见的 HTML、CSS、JavaScript 事件代码示例

      • 鼠标事件示例
      • 键盘事件示例
      • 表单事件示例


在学习 HTML、CSS 和 JavaScript 事件相关知识时,通过实际的代码示例能更直观地理解事件的应用和处理方法。下面是一些常见事件的代码示例,供大家参考学习:

鼠标事件示例

DOCTYPE html>
<html>
<head>
    <title>鼠标事件示例title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: #f00;
        }
    style>
head>
<body>
    <div class="box" id="box">div>

    <script>
        var box = document.getElementById("box");
        
        // click事件示例
        box.addEventListener("click", function() {
            console.log("点击了红色方块");
        });

        // mouseover事件示例
        box.addEventListener("mouseover", function() {
            console.log("鼠标移入红色方块");
        });

        // mouseout事件示例
        box.addEventListener("mouseout", function() {
            console.log("鼠标移出红色方块");
        });
    script>
body>
html>

键盘事件示例

DOCTYPE html>
<html>
<head>
    <title>键盘事件示例title>
head>
<body>
    <input type="text" id="input">

    <script>
        var input = document.getElementById("input");
        
        // keydown事件示例
        input.addEventListener("keydown", function(event) {
            console.log("按下键盘键:" + event.key);
        });

        // keyup事件示例
        input.addEventListener("keyup", function(event) {
            console.log("松开键盘键:" + event.key);
        });
    script>
body>
html>

表单事件示例

DOCTYPE html>
<html>
<head>
    <title>表单事件示例title>
head>
<body>
    <form id="form">
        <input type="text" id="username" placeholder="用户名">
        <input type="password" id="password" placeholder="密码">
        <button type="submit">提交button>
    form>

    <script>
        var form = document.getElementById("form");

        // submit事件示例
        form.addEventListener("submit", function(event) {
            event.preventDefault(); // 阻止表单提交
            console.log("表单提交");
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;
            console.log("用户名:" + username + ",密码:" + password);
        });
    script>
body>
html>

通过以上代码示例,可以更加直观地了解 HTML、CSS 和 JavaScript 事件的使用方法,希望能够帮助大家更好地学习和理解事件相关知识。

你可能感兴趣的:(前端学习,html,css,javascript,html5,css3,前端)