如何在多个元素上使用鼠标悬停事件

How to use onmousehover event on multiple elements?

本文关键字:鼠标 悬停 事件 元素      更新时间:2023-09-26
<html>
    <head>
        <script>
            function show_function() {
                var example_image=document.getElementById("example_image");
                example_image.src="example_one.png";
            }
            function hide_function() {
                var example_image=document.getElementById("example_image");
                example_image.src="example.png";
            }
        </script>
    </head>
<body>
    <div class="one" onmouseover="show_function()" onmouseout="hide_function()">
        <img id="example_image" src="example.png">
    </div>
    <div class="two" onmouseover="show_function()" onmouseout="hide_function()">
        <img id="example_image" src="example.png">
    </div>
</body>
</html>

当我将鼠标悬停在第一个div上时,图像会发生变化。但是当我将鼠标悬停在第二个div 上时,第一个div 的图像也会发生变化。

有谁知道如何只在javascript中做到这一点?

就像丹科说的,ID必须是唯一的。下一步是将变量插入函数:

<html>
<head>
<script>
function show_function(id, hide)
{
    var example_image=document.getElementById(id);
    if(hide){
    example_image.src="example.png";
    } else{
    example_image.src="example_one.png";
    }
}
</script>
</head>
<body>
<div class="one" 
onmouseover="show_function('example_image1')" 
onmouseout="show_function('example_image1', true)" />
<img id="example_image1" src="example.png">
</div>
<div class="one" 
onmouseover="show_function('example_image2')" 
onmouseout="show_function('example_image2', true)" />
<img id="example_image2" src="example.png">
</div>
</body>
</html>

或者你也可以这样:

<img src="example.png" 
onmouseover="this.src='example_one.png';" 
onmouseout="this.src='example.png';" />

希望对您有所帮助!

你可以

这样做:

show_function = function (container) {
    container.childNodes[1].src = "example_one.png";
}
hide_function = function (container) {
    container.childNodes[1].src = "example.png";
}

然后在 HTML 中,将this传递给函数:

<div class="one" onmouseover="show_function(this)" onmouseout="hide_function(this)">
    <img id="example_image" src="example.png">
</div>
<div class="two" onmouseover="show_function(this)" onmouseout="hide_function(this)">
    <img id="example_image" src="example.png">
</div>

我认为你想要div.的第一个子节点[0]并将悬停的对象传递到回调中。

function show(e){ 
  document.getElementById('label').innerHTML = e.children[0].id;
  e.style.border = "solid 2px red";
  } 
function hide(e){ 
  
  e.style.border = "0";
  
  }
<div class="one" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="one" >
</div>
<div class="two" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="two">
</div>
<p id='label' ></p>