如何反转点击时内容视图的打开动画

问题描述 投票:0回答:1

function moveRectangles(event) {
  var rectangles = document.querySelectorAll('.rectangle');
  var gap = 5; // Gap between rectangles
  var distance = 100; // Distance to move each rectangle

  // Check if the click target is a rectangle
  if (event.target.classList.contains('rectangle')) {
    // Move the rectangles to the left to create a gap
    for (var i = 0; i < rectangles.length; i++) {
      rectangles[i].style.left = (i * -(distance + gap)) + 'px';
    }
  } else {
    // Reset the position of all rectangles to 0
    for (var i = 0; i < rectangles.length; i++) {
      rectangles[i].style.left = '0px';
    }
  }

  // Prevent click event from bubbling up to the body
  event.stopPropagation();
}
/* CSS to style the rectangles */

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.rectangle {
  width: 100px;
  height: 50px;
  background-color: orange;
  position: absolute;       /* Set position to absolute */
  border-radius: 10px;      /* Adjust border radius for rectangle shape */
  transform: rotate(90deg); /* Rotate rectangles by 90 degrees */
  transform-origin: center; /* Set transform origin to the center */
  transition: left 0.5s;    /* Add transition for smooth movement */
  cursor: pointer;          /* Change cursor to pointer when hovering over rectangles */
}
<div class="container" onclick="moveRectangles(event)">
  <div class="rectangle" style="left: 0px;"></div>
  <div class="rectangle" style="left: 0px;"></div>
  <div class="rectangle" style="left: 0px;"></div>
  <div class="rectangle" style="left: 0px;"></div>
  <div class="rectangle" style="left: 0px;"></div>
  <div class="rectangle" style="left: 0px;"></div>
</div>

我尝试制作这样的功能,当有人单击除矩形之外的空白空间时,动画应该反转,但我没有掌握反转它的功能,因为它只是坐着而不做任何事情。就像如果我首先单击矩形,然后通常它会打开或升起您想要向左侧调用的任何内容,那么当我单击空白区域时,它应该反转该操作。

应该是这样的: these are the steps of the whole animation

javascript html css animation
1个回答
0
投票

你的

if condition
错了。您正在检查该元素是否包含具有类
.rectangle
的元素。相反,您可以检查某个索引处某个元素的
left
属性。例如:

// Check if the click target is a rectangle
      if (event.target.classList.contains('rectangle') && rectangles[1].style.left === "0px") {
      // the condition above now also checks if the second rectangle's left is 0px
      // Move the rectangles to the left to create a gap
      for (var i = 0; i < rectangles.length; i++) {
        rectangles[i].style.left = (i * -(distance + gap)) + 'px';
      }

在此逻辑中,我们检查第二个矩形的

left
属性是否等于 0px,如果是,我们将其动画化,否则我们反转动画。

编辑:这与以前有什么不同? 在 if-else 条件检查父元素是否有类为

.rectangle
的子元素之前。因此,只有在没有矩形的情况下,else 语句才会运行。现在,它检查第二个元素的 left 属性是否为 0px,在这种情况下,如果它不是 0px,则将运行 else 语句。

© www.soinside.com 2019 - 2024. All rights reserved.