【问题标题】:How to calculate absolute position of transformed div如何计算转换后的div的绝对位置
【发布时间】:2013-06-01 15:05:36
【问题描述】:

当您在 div 上使用transform 时,绝对定位不再像您预期的那样工作,并且似乎需要手动计算。例如,当您希望 div 位于容器底部时:

div{
    position:absolute;
    bottom:0%;
}

但是如果你像-webkit-transform:rotateX(angle); 那样转换这个div,它就不会在容器的底部。容器之间的位置取决于其大小。

我创建 jsfiddle 来说明这一点,并展示我想要达到的目标:http://jsfiddle.net/9NHJt/

这是我使用的代码:

<div class="container"> height: 150px;
    <div class="inner"></div>
</div>

<div class="container" style="height:250px"> height: 250px;
    <div class="inner"></div>
</div>

<div class="container"> desired result
    <div class="inner" style="bottom:-19px"></div>
</div>


.container{
    margin-top:30px;
    position:relative;
    width:500px;
    height:150px;
    -webkit-perspective:1000px;
    border:1px solid black
}

.inner{
    -webkit-transform:rotateX(45deg);
    background:rgba(238, 238, 238, 0.8);
    border:1px dashed black;
    position:absolute;    
    width:100%;
    height:100%;
    bottom:0%; /* Needs to be calculated */
}

那么,有没有办法在没有 javascript 的情况下解决这个问题?或者如何用js计算正确的底部位置?

【问题讨论】:

    标签: css trigonometry webkit-transform webkit-perspective


    【解决方案1】:

    好的,你应该添加一个标签:'geometry'。 首先,记住正弦和余弦,然后用计算器: 绕 x 轴旋转 45 度
    45 的 cos 大约是 0,7,然后//value of cos for 45 degrees
    0.7*150=106 //the height of the rectangle afther transformation
    (150-106)/2 //the space remaining in the parent up and down the element divided by 2
    结果是 22,这是您需要的正顶部或负底部。

    第二个块也一样:(250-(0.7*250))/2 = 37.5

    如果更改角度,请记住重新计算角度值。数字越四舍五入,您就越准确。请记住,对于许多标签来说,计算可能很繁重。

    【讨论】:

    • 谢谢,看起来很棒。但我不明白-webkit-perspective 的值如何在计算中被忽略?
    • 我认为因为透视在那里没有效果(在谷歌浏览器中)..groups.google.com/a/chromium.org/forum/?fromgroups#!msg/…
    • 如果您需要了解透视的转换:stackoverflow.com/questions/8029605/…
    • webkit 透视图只能在 chrome 和 safari 上工作,但如果你禁用了这个功能,它就不能在任何地方工作 chrome://gpu/
    • 透视在 Firefox 中同样有效,即使没有 -moz- 前缀
    【解决方案2】:

    这里有一个Fiddle 来检查,如果这是你想要的,请告诉我?

    .inner{
        -webkit-transform:rotateX(45deg);
        background:rgba(238, 238, 238, 0.8);
        border:1px dashed black;
        position:absolute;    
        width:100%;
        height:100%;
        /* bottom:0%; removed */
    }
    

    【讨论】:

    • 不,这不是正确的解决方案。第二个内部与容器底部不匹配。如果我希望.inner 成为top:0%,或者.containerheight:100%,该怎么办?
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多