将鼠标指针移动到图像上

move the mouse pointer over an image

本文关键字:图像 移动 鼠标指针      更新时间:2023-09-26

我在一个HTML页面中有四个图像:1.png、2.png、3.png和4.png。当用户将鼠标指针移到1.png时,2.png应该替换4.png;同样,如果鼠标指针移向2.png,3.png应该被1.png替换。

这是我的代码:

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <script type="text/javascript">
            function image1_mouseover()
            {
                var img2 = document.getElementById('img2');
                var img4 = document.getElementById('img4');
                img2.setAttribute('src','exercice1/4.png');
                img2.setAttribute('id','img4');
                img4.setAttribute('src','exercice1/2.png');
                img4.setAttribute('id','img2');
            }
            function image2_mouseover()
            {
                var img1 = document.getElementById('img1');
                var img3 = document.getElementById('img3');
                img1.setAttribute('src','exercice1/3.png');
                img1.setAttribute('id','img3');
                img3.setAttribute('src','exercice1/1.png');
                img3.setAttribute('id','img1');
            }
            function image3_click()
            {
            }
        </script>
        <style type="text/css">
            table
            {
                margin-left:auto;
                margin-right:auto;
            }
        </style>
    </head>
    <body>
        <table class="centrer">
            <tr>
                <td><img src="exercice1/1.png" alt="Image 1" id="img1" onmouseover="image1_mouseover()"></td>
                <td><img src="exercice1/2.png" alt="Image 2" id="img2" onmouseover="image2_mouseover()"></td>
            </tr>
            <tr>
                <td><img src="exercice1/3.png" alt="Image 3" id="img3"></td>
                <td><img src="exercice1/4.png" alt="Image 4" id="img4"></td>
            </tr>
        </table>
    </body>
</html>

一开始,当我把鼠标移到1.png,2.png代替4.png时,它是有效的。但后来我把鼠标移动到2.png,1.png并不能代替3.png,相反,我必须把鼠标移过4.png才能实现这一点。

怎么了?

我想您对图像发生的事情感到困惑。

与其切换它们的属性,不如切换图像的位置?

function switch_images(i1,i2) {
    var e1 = document.getElementById('img'+i1),
        e2 = document.getElementById('img'+i2),
        e1parent = e1.parentNode;
    e2.parentNode.appendChild(e1);
    e1parent.appendChild(e2);
}

然后使用这个HTML:

<table class="centrer">
    <tr>
        <td><img src="exercice1/1.png" alt="Image 1" id="img1" onmouseover="switch_images(2,4)"></td>
        <td><img src="exercice1/2.png" alt="Image 2" id="img2" onmouseover="switch_images(1,3)"></td>
    </tr>
    <tr>
        <td><img src="exercice1/3.png" alt="Image 3" id="img3"></td>
        <td><img src="exercice1/4.png" alt="Image 4" id="img4"></td>
    </tr>
</table>