2017-02-21 96 views
1

我有一個包含小div的一個div,每有一個綵球的background-imageCSS變換的僞3D效果?

<div class="container"> 
    <div class="ball" style="left: 100px; top: 50px;"> 
    <div class="ball" style="left: 120px; top: 100px;"> 
    <div class="ball" style="left: 140px; top: 150px;"> 
    <div class="ball" style="left: 160px; top: 200px;"> 
    <div class="ball" style="left: 180px; top: 250px;"> 
</div> 

現在我想建立某種形式的僞3D效果,其中具有的較小值的球'頂部'更小,更靠近底部的球看起來更大。

我讀過一些關於CSS3轉換和透視的一些小技巧,但我不知道該怎麼做。

有什麼辦法調整div的的widthheight,基於其top - 屬性?

+0

[https://jsfiddle.net/5g205zub/]怎麼樣? – pol

+0

謝謝,但球也可以改變位置,所以尺寸真的要取決於頂級屬性... – Dylan

+0

@Dylan我的答案是否適合你? –

回答

1

您可以創建一個變量來存儲css中的最高值,如style="--top: 10px",並在後面像var(--top)一樣使用它。

更新

您需要使用JavaScript來設置使用setProperty方法--top屬性,並且可以使用getPropertyValue方法得到的--top值。請參閱動態更改--top onclick事件的示例,該事件會更改--top值,widthheight會自動進行調整。

代碼段

balls = document.getElementsByClassName('ball'); 
 

 
Array.prototype.forEach.call(balls, function(ball){ 
 
\t ball.onclick = function() { 
 
\t \t ball.style.setProperty('--top', parseInt(ball.style.getPropertyValue('--top')) * 1.2 + 'px') 
 
    } 
 
})
.ball { 
 
    background-image:url(https://upload.wikimedia.org/wikipedia/commons/e/ec/Soccer_ball.svg); 
 
    width: calc(var(--top) * 1.2); 
 
    height: calc(var(--top) * 1.2); 
 
    background-size: cover; 
 
    position: absolute; 
 
}
<div class="container"> 
 
    <div class="ball" style="left: 100px; --top: 50px;"></div> 
 
    <div class="ball" style="left: 120px; --top: 100px;"></div> 
 
    <div class="ball" style="left: 140px; --top: 150px;"></div> 
 
    <div class="ball" style="left: 160px; --top: 200px;"></div> 
 
    <div class="ball" style="left: 180px; --top: 250px;"></div> 
 
</div>

+0

謝謝,但頂級屬性需要動態設置。因此,除非有辦法讓top變量與真正的top屬性保持同步,否則這是行不通的。 – Dylan

+0

@Dylan查看更新的答案。 –

0

您可以設置包含的元素上的真正的3D變換:

.container { 
 
    width: 400px; 
 
    height: 300px; 
 
    position: relative; 
 
    perspective: 300px; 
 
} 
 

 
.inner { 
 
    width: 100%; 
 
    height: 100%; 
 
    position: relative; 
 
    transform: rotateX(60deg); 
 
    transform-style: preserve-3d; 
 
    border: solid 2px green; 
 
} 
 

 
.ball { 
 
    width: 30px; 
 
    height: 30px; 
 
    border-radius: 50%; 
 
    background-color: lightblue; 
 
    position: absolute; 
 
    transform: rotateX(-60deg); 
 
    transform-style: preserve-3d; 
 
}
<div class="container"> 
 
<div class="inner"> 
 
    <div class="ball" style="left: 100px; top: 50px;"></div> 
 
    <div class="ball" style="left: 120px; top: 100px;"></div> 
 
    <div class="ball" style="left: 140px; top: 150px;"></div> 
 
    <div class="ball" style="left: 160px; top: 200px;"></div> 
 
    <div class="ball" style="left: 180px; top: 250px;"></div> 
 
</div> 
 
</div>