在屏幕外翻译元素的最佳方式



我使用CSS3转换已经有一段时间了,但有一点有点麻烦,那就是百分比与要移动的元素有关,而不是与父元素有关。这是有道理的,但它带来了一些情况,我不确定最好的解决方法。

例如,如果我们想象一个元素绝对位于屏幕上,你会如何将该元素转移到屏幕外?元素的尺寸可能很小,比如200x200像素,这意味着如果不进行一些计算,就无法使用百分比。

我脑海中的选择是:

1) 将元素放入屏幕大小的容器中,然后将容器平移100%。

2) 使用translateZ将元素提升到其自己的GPU层,将更改或translate3d,然后应用适当的左/右属性。

3) 使用getBoundingClientRect确定元素相对于视口的位置,进行计算以确定为了使元素离开屏幕而需要应用的像素距离,然后将该值应用为内联转换样式。

我能就处理这种情况的最佳方法得到一些建议吗?需要考虑的因素是,该技术将用于响应现场,因此任何价值计算都需要在应用该技术之前立即进行。

要在屏幕外或父级之外定位内容,我所做的就是使用位置属性。对我来说,这似乎很自然;上/左/右/下是可设置动画的,因此它们可以很好地转换;第三个好处是对这些属性有很好的支持,所以即使浏览器很古老,后备措施也是定位有效,而不是转换。

考虑以下内容:

<div class="parent">
    <div class="from-the-bottom"></div>
</div>

CSS:

.parent {
    height: 400px;
    width: 400px;
    background-color: #ccc;
    position: relative; /*Make sure the parent has positioning*/
    overflow: hidden; /*Hide its overflow*/
}
.from-the-bottom {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 100%;  /*100% top pushes the element fully out of view at the bottom*/
    left: 0;
    right: 0;
    background-color: yellowgreen;
    transition: top .3s ease;
}
.parent:hover .from-the-bottom {
    top: 0; /*Changing the top value positions the element within the context of it's parent*/
}

这应该做到:

.offscreen {
    position: fixed;
    top: 0;
    left: 0;
    transform: translateX(-100%);
 }

position: fixed相对于视口(浏览器窗口)放置元素。将fixed视为与absolute相同,只是它是相对于视口的,忽略所有其他div。

然后我们用top: 0left: 0 将元素放置在左上角

我们有这个:

          ______________
         |[Element]     |
         |              |
         |              |
         |  (Viewport)  | 
         |              |
         |              |
         |______________| 

然后,我们将元素向左移动其自身宽度的100%,从而有效地将其隐藏起来,使用transform: translateX(-100%):

          ______________
[Element]|              |
         |              |
         |              |
         |  (Viewport)  | 
         |              |
         |              |
         |______________| 

注意:这不受放大/缩小的影响,也不会导致溢出(滚动)

最新更新