【问题标题】:Rotate squares on mouse hover JavaScript [closed]在鼠标悬停JavaScript时旋转方块[关闭]
【发布时间】:2021-08-15 07:49:14
【问题描述】:

我需要通过init() 重新定位此 HTML 代码中的 5 个方块 函数和reposition() 函数。
我看着另一个 网站的 HTML/CSS 主题,但我什么也没找到 对这些信息很有帮助。
以下是问题:

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;
        }
        #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() {
        }
        function reposition() {
        }
    </script>
</head>
<body onload="init()">
    <h1>Reposition the squares</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>

【问题讨论】:

  • 您好,您知道如何添加事件监听器吗?
  • 是的,有点,但我不知道如何解决这个问题。

标签: html css rotation


【解决方案1】:

有两种方法可以解决这个问题。我假设您希望在将鼠标悬停在一个正方形上时旋转它,因此,您可以使用 CSS 样式来执行此操作。就如何设置 div 或任何其他 HTML 元素的样式,例如,您可以使用 .square 类在鼠标悬停时旋转所有内容,如下所示:

.square:hover {
    transform: rotate(180deg);
}

如果您想解决这个问题,请将transition: 0.5s; 添加到您的.square 选择器中。

如果你想在 JavaScript 中做同样的事情,确保你添加了我刚才说的那个过渡,然后你可以选择一个特定的正方形来旋转它的 id,如下所示:

document.getElementById("carre1").addEventListener("mouseenter", function() {
    document.getElementById("carre1").style.transform = "rotate(180deg)";
});

这基本上做同样的事情,但当你的鼠标离开方块时不会恢复方块。

编码愉快!

【讨论】:

  • 非常感谢,解决了!祝你晚上愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多