Javascript 鼠标悬停按钮

Javascript Mouseover button

本文关键字:按钮 悬停 鼠标 Javascript      更新时间:2023-09-26

我想我已经接近做到这一点了,但是当用户将鼠标悬停在提交按钮上时,我不知道如何更改提交按钮的颜色,我也是新手javascript,所以任何帮助将不胜感激

这是我的代码:

<html>
    <head>
        <title>JavaScript</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script>
            function getName(){
            var name;
            name = window.prompt("Enter your name", "");
            greeting = "User Information for " + name;
            var txt=    document.getElementById('txtWelcome');
            txt.innerHTML=greeting;
            }
    function over() {
            document.getElementById("Submit").style.background  = 'Blue';
        }
        function out() {
            document.getElementById("Submit").style.background = 'Yellow';
        }

    </script> 
</head>
<body onload="getName()">
        <form class="basic_form">
            <h1 id="txtWelcome"></h1>
    <p>Please input your login details</p>
            <fieldset>
                <label class="form_labels">Username:</label>
                <input class="form_fields" type="text"  name="username"><br>
                <label class="form_labels">E-Mail:</label>
                <input class="form_fields" type="email" name="email"><br>
                <label class="form_labels">Password:</label>
                <input class="form_fields" type="password" name="password">
                <input class="form_buttons" type="Submit" value="Submit"><br>
            </fieldset>
        </form>
</body>

这是javascript解决方案:

var submitButton = document.getElementById('submit');
submitButton.addEventListener('mouseover', function() {
    this.style.backgroundColor='blue';
});
submitButton.addEventListener('mouseout', function() {
    this.style.backgroundColor='yellow';
});

https://jsfiddle.net/hsxdkkp6/

但是为什么不直接使用 css呢?

input[type=submit]:hover {
  background-color: red;
}

https://jsfiddle.net/jkkj8dvt/