从相对于元素的原点开始动画叠加

时间:2019-01-31 07:21:32

标签: javascript css

我正在尝试制作一个叠加层动画,以从触发该叠加层的UI元素扩展到全屏。例如,我有一个按钮,当单击该按钮时会显示一个叠加层,我希望该叠加层从该按钮展开(在该按钮的上方或下方,此时不重要)。

我目前正在使用类似于this question上第二个答案的方法。问题是position: fixed规则从文档流中删除了覆盖(示例中的#box),因此其位置是相对于整个文档的。

所以我想问题是,是否可以保持流量,还是使用相对定位来获得所需的结果?目前,我唯一想到的解决方案是使用JS在加载时适当地设置transform: translate的位置,并调整其大小以匹配按钮的位置。如果有更优雅的方法可以实现这一点,我会很乐意。

编辑:以下代码几乎逐字逐句地从上述问题中剔除,我想添加一个button或类似的交互元素,使该动画相对于其位置而不是相对于该位置视口。

document.getElementById('box').addEventListener('click', (e) => e.target.classList.toggle('fullscreen'));
    #box {
        position: fixed;
        cursor: pointer;
        background-color: red;
        width: 100vw;
        height: 100vh;
        top: 0;
        left: 0;
        transform: translate(50px, -50px) scale(0.1);
        transform-origin: left bottom;
        transition: all 0.7s ease;
    }

    #box.fullscreen {
          transform: translate(0, 0) scale(1);
    }
<div id="box"></div>

编辑:再想一想,动画背景变化(例如radial-gradient)也可以解决问题,我只需要隐藏元素,直到动画完成,但这可能是一个选择。动画的起源是全屏效果的重要组成部分。如果我在此期间取得任何进展,将会更新。任何输入都非常感谢!

1 个答案:

答案 0 :(得分:1)

好吧,我做了一些更改,它应该可以按照您的要求工作。请务必阅读评论,以便您理解其思想。

$(".expand").on("click", function() {
  var rect = this.getBoundingClientRect();
  var box = $("#box");
  // make sure that the position of the overlay start from the clicked element
  box.css({ left:rect.left , top: rect.top + rect.height }); 
   
  box.toggleClass("fullScreen").delay(500).queue(function() {
    box.css({ left:0 , top: 0 }); // the toggle finished then reset the left and top so it overlay the whole screen 
  });

});
/* YOUR BOX */
#box{
  position: fixed;
  cursor: pointer;
  background-color: red;
  /* make the box full screen */
  /* scale it down to 0.1 (10%) initially,
     make an offset from bottom left */
  -ms-transform: translate(0px, 0px) scale(0.1); /* IE9 */
  -ms-transform-origin: left top; /* IE9 */
  transform: translate(0px, 0px) scale(0.1);
  transform-origin: left top;
  width:0;
  height:0;
  overflow:hidden;
  /* smooth transition (IE10+) */
  -webkit-transition: all 0.7s ease;
          transition: all 0.7s ease;
}

/* ADD THIS CLASS WITH JS */
#box.fullScreen {
  width: 100vw; /* IE9+ */
  height:100vh; /* IE9+ */
  -ms-transform: translate(0px, 0px) scale(1); /* IE9 */
  transform: translate(0px, 0px) scale(1);
}

.expand{

margin:auto;
width:100px;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="expand">Click Me</div>


<div id="box">your content</div>