2013-06-01 38 views
0

當您在div上使用transform時,絕對定位不再按預期工作,而且似乎需要手動計算。例如,當你希望你的div是在集裝箱你做的底部:如何計算轉換後的div的絕對位置

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

但是,如果你改變這個div像-webkit-transform:rotateX(angle);它不會在容器的底部。取決於其大小,容器之間的某處位於容器之間。

我創建的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計算正確的底部位置?

回答

0

好的,你應該添加一個標籤:'幾何'。 第一件事,記得正弦和餘弦,則取一個計算器:繞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

記住,如果你改變它重新計算的角度的值。數字越圓潤,你越準確。請記住,許多標籤的計算可能很重。

+0

謝謝,看起來不錯。但我不明白'-webkit-perspective'值在計算中可以忽略? – nukl

+0

我認爲,因爲透視沒有影響(在谷歌鉻).. https://groups.google.com/a/chromium.org/forum/?fromgroups#!msg/chromium-bugs/BdyVDwXelvU/Q6GWJk3LndgJ –

+0

如果你需要知道什麼是轉變的角度來看:http://stackoverflow.com/questions/8029605/what-is-the-math-behind-webkit-perspective –

0

這裏是一個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 */ 
} 
+0

不,這不是正確的解決方案。第二個內部不符合容器底部。例如,如果我想'.inner'爲'top:0%',或'.container'爲'height:100%'? – nukl