jQuery如何实现让子div向右动画移出父div?

3

我想要动画展示子div的宽度超出父div。 在我提供的代码中,子div的动画效果只在父div内部。

请帮忙看一下。 jsfiddle

$(document).ready(() => {
  drop = false;
  $(".parent").click(() => {
    if (drop == true) {
      $(".child").animate({
        width: "0px"
      });
      drop = false;
    } else if (drop == false) {
      $(".child").animate({
        width: "200px"
      });
      drop = true;
    }
  })
});
.parent {
  width: 40%;
  height: 200px;
  position: relative;
  background-color: red;
}

.child {
  width: 0px;
  height: 200px;
  position: absolute;
  right: 0;
  top: 0;
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <div class="child">
  </div>
</div>


1
欢迎来到Stack Overflow。请查看[ask]和[edit]您的问题以包含您的代码。您可以使用编辑器工具栏上的[<>]按钮创建可运行的Stack Snippet。外部链接是可以的,但仅当相关代码也在此处包含时,因为外部链接可能会随时间而中断或更改,这个问题对其他用户不再有用。另外,您所询问的内容有点不清楚 - 您所说的“在父级之外动画”是什么意思?如果您不想重叠父级,请将其从子级更改为同级。 - FluffyKitten
2个回答

2

当您说希望子元素向右动画,我认为您是指它要从父元素滑出。

根据您在jQuery中已经设置了宽度,所以您只需要将right设置为负数,即可使其向相反方向延伸,例如:

  $(".child").animate({width: "200px", right: "-200px" });

然后要重置它,只需设置 right:0,例如:
  $(".child").animate({width: "0px", right:"0"});

工作片段:

$(document).ready(()=> {

    drop = false;
  
  $(".parent").click(()=> {
    if(drop == true) {   
      $(".child").animate({width: "0px", right:"0"});
      drop = false;
      
    } else if(drop == false) {  
      $(".child").animate({width: "200px", right: "-200px" });
      drop = true;     
    }
  })

});
.parent {
  width: 40%;
  height: 200px;
  position: relative;
  background-color: red;
}

.child {
  width: 0px;
  height: 200px;
  position: absolute;
  right: 0;
  top: 0;
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
   <div class="parent">     
      <div class="child">        
      </div>     
   </div>
</body>


1
你可以将宽度更改为400像素,它将扩展到400像素。你可以使用100%来匹配红色框或使用150%来比红色框多50%。
如果你想向右扩展,请将.child的css中的right: 0更改为left: 0

$(document).ready(() => {
  drop = false;
  $(".parent").click(() => {
    if (drop == true) {
      $(".child").animate({
        width: "0px"
      });
      drop = false;
    } else if (drop == false) {
      $(".child").animate({
        width: "400px"
      });
      drop = true;
    }
  })
});
.parent {
  width: 40%;
  height: 200px;
  position: relative;
  background-color: red;
}

.child {
  width: 0px;
  height: 200px;
  position: absolute;
  left: 0;
  top: 0;
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <div class="child">
  </div>
</div>


1
我希望子div向右扩展而不是向左。 - DevNewbie
如上所述,将“right”更改为“left”。答案已更新。这符合您的需求吗? - Rado
不完全是,现在子元素正在父元素内从左到右进行动画。我希望它仍然在右侧并向右扩展。 - DevNewbie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接