首页 > 解决方案 > 当我将鼠标放在 JavaScript 上时,我需要重新定位方块。我怎么做?

问题描述

A.在“init”函数中添加“reposition”函数所需的代码,只要将鼠标悬停在与 CSS 类“square”关联的页面元素上,就会调用该代码。B.修改“重新定位”功能,使其允许您重新定位正方形相对于对角线对称。为此,只需颠倒该正方形的水平和垂直位置即可。注意:粉色方块不会移动,因为它正好在对角线上(水平和垂直位置相同)。

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Reposition the squares</title>
    <style>
        #bac {
            position: relative;
            width: 400px;
            height: 400px;
            border: 1px solid red;
            text-align: center;
        }
        .square {
            width: 50px;
            height: 50px;
        }
        #square1 {
            position: absolute;
            left: 300px;
            top: 200px;
            background-color: red;
        }
        #square2 {
            position: absolute;
            left: 120px;
            top: 75px;
            background-color: blue;
        }
        #square3 {
            position: absolute;
            left: 50px;
            top: 240px;
            background-color: orange;
        }
        #square4 {
            position: absolute;
            left: 350px;
            top: 0px;
            background-color: black;
        }
        #square5 {
            position: absolute;
            left: 50px;
            top: 50px;
            background-color: pink;
        }
    </style>
    <script>
        function init() {
        //Code here

        }


        function reposition() {
        //code here
        }
    </script>
</head>
<body onload="init()">
    <h1>Reposition the squares</h1>
    <div id="bac">
        <div id="square1" class="square"></div>
        <div id="square2" class="square"></div>
        <div id="square3" class="square"></div>
        <div id="square4" class="square"></div>
        <div id="square5" class="square"></div>
    </div>
</body>
</html>

标签: javascripthtmlcsshovercss-animations

解决方案


你可以使用这个脚本

<script>
    const squares = document.querySelectorAll(".square");
    for(let i = 0; i < squares.length; i++){
        squares[i].addEventListener("mouseover",(e)=>{
            let v = getComputedStyle(squares[i]);
            let top = v.getPropertyValue('top').replace(/\D/g, "");
            let left = v.getPropertyValue('left').replace(/\D/g, "");;
            if(top == left){
                e.preventDefault();
            }
            else{
                squares[i].style.top = left+"px";
            }
        })
    }
</script>

首先我打电话给所有的方格,然后我为每个方格制作了一个事件

其次,当我将鼠标放在其上时,我搜索了顶部和左侧属性

第三,我只从没有“px”的属性中得到数字,这就是我使用正则表达式的原因

最后,我为每个不匹配的正方形给出了相同的顶部和左侧值

也许有人可以给你一个简短的代码,但这是我的解决方案(我还是学生),它对我有用。

注意:橙色方块将隐藏在粉红色方块下方,因为两者的顶部和左侧值相同。


推荐阅读