You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

鼠标悬停触发正方形对角线对称重定位的JavaScript实现需求

解决方案

核心修改点

  • init()函数:页面加载完成后选中所有携带square类的元素,为每个元素绑定鼠标悬停事件,触发时将当前元素作为参数传入reposition()函数调用。
  • reposition()函数:接收目标正方形元素作为入参,读取元素当前的水平(left)、垂直(top)定位值,直接交换二者后重新赋值给元素样式,实现沿对角线对称重定位。

完整运行代码

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>重定位正方形</title>
    <style>
        #bac {
            position: relative;
            width: 400px;
            height: 400px;
            border: 1px solid red;
            text-align: center;
        }
        .square {
            width: 50px;
            height: 50px;
        }
        #carre1 {
            position: absolute;
            left: 300px;
            top: 200px;
            background-color: red;
        }
        #carre2 {
            position: absolute;
            left: 120px;
            top: 75px;
            background-color: blue;
        }
        #carre3 {
            position: absolute;
            left: 50px;
            top: 240px;
            background-color: orange;
        }
        #carre4 {
            position: absolute;
            left: 350px;
            top: 0px;
            background-color: black;
        }
        #carre5 {
            position: absolute;
            left: 50px;
            top: 50px;
            background-color: pink;
        }
    </style>
    <script>
        function init() {
            const squares = document.querySelectorAll('.square');
            squares.forEach(square => {
                square.addEventListener('mouseenter', function() {
                    reposition(this);
                });
            });
        }
        function reposition(el) {
            const computedStyle = window.getComputedStyle(el);
            const currentLeft = parseInt(computedStyle.left);
            const currentTop = parseInt(computedStyle.top);
            el.style.left = `${currentTop}px`;
            el.style.top = `${currentLeft}px`;
        }
    </script>
</head>
<body onload="init()">
    <h1>重定位正方形</h1>
    <div id="bac">
        <div id="carre1" class="square"></div>
        <div id="carre2" class="square"></div>
        <div id="carre3" class="square"></div>
        <div id="carre4" class="square"></div>
        <div id="carre5" class="square"></div>
    </div>
</body>
</html>

内容的提问来源于stack exchange,提问作者sudo_ p4rted

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 01:06:01