如何在鼠标悬停时更改按钮上的文本?

How do i change the text on a button on mouse hover?

我需要制作一个按钮,当光标在它上面时更改其中的文本,并在光标离开框时将其更改回来。 我已经在 VScode 上尝试使用“document.getElementById().innerHTML”,但它只是在光标移动时更改文本,并且不会返回到原始文本。

button  {
    
    background-color: green;
    border-color: white;
    border-radius: 10px;
    align-self: center;
}
body  {
    background-color: black;
}

h1  {
    color:green;
    text-align: center;
}

p   {
    color: chartreuse;
    font-family: Verdana;
    font-size: 12px;
}
button:hover{
    background: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="website.css">

</head>
<body>
<h1>Web Page</h1>

<!-- Buttons -->
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click to display Date and Time</button>
<p id="demo"></p>

<button type="button"
onmouseover="this.innerHTML = Date()"
onmouseout="document.getElementById">What time is it</button>
<script>
    var x = "What time is it";
    document.getElementById("time").innerHTML = x;
</script>

我的做法是在我的按钮中放置两个 <span>。第一个 <span> 将包含您要默认显示的文本。第二个 <span> 将包含您要在 hover 上显示的文本。此跨度默认隐藏。

然后,您可以向您的按钮添加一个事件侦听器。在 mouseover 上,隐藏默认文本并显示包含悬停文本的 span。在 mouseleave 事件侦听器中,执行相反的操作。

HTML:

<button id="myid">
  <span class="default-text">Text 1</span>
  <span class="hover-text" style="display: none;">Text 2</span>
</button>

JS:

var button = document.getElementById('myid')

button.addEventListener('mouseover', function() {

    this.querySelector('.hover-text').style.display="block";
    this.querySelector('.default-text').style.display="none";
});

button.addEventListener('mouseleave', function() {

    this.querySelector('.default-text').style.display="block";
    this.querySelector('.hover-text').style.display="none";
});

您可以使用 mouseentermouseleave 事件,然后可以更改按钮的 innerHTML。

const btnEle = document.getElementById("btn");
btnEle.addEventListener('mouseenter', e => {
  btnEle.innerHTML = "Save";
});

btnEle.addEventListener('mouseleave', e => {
    btnEle.innerHTML = "Submit";
});
<!DOCTYPE html>  
<html>
    <head>
        <title>
              
        </title>
    </head>
      
    <body>
        <div>
            <button id="btn">Submit</button>
        </div>
    </body>
</html>