当我将鼠标放在JavaScript上时,我需要重新定位方块。我该怎么做? [英] I need to reposition the squares when I put the mouse over JavaScript. How do I do that?

查看:24
本文介绍了当我将鼠标放在JavaScript上时,我需要重新定位方块。我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<!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>

推荐答案

您可以只使用此脚本

<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";的属性获得数字,这是我使用Regex的原因

最后,我为每个不匹配的方块提供了相同的顶部和左侧值

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

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

这篇关于当我将鼠标放在JavaScript上时,我需要重新定位方块。我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆