[英]How to animate with relative transforms in css?
我有兩個盒子:
<div class='item' style='transform:translateY(100px)'>
</div>
<div class='item' style='transform:translateY(300px)'>
</div>
它們都使用相同的類:
.item {
position:absolute;
background:red;
animation:float 3s ease-in-out infinite;
width:100px;
height:100px;
}
動畫看起來像:
@keyframes float {
from, to { transform: translateY(-10px); }
50% { transform: translateY(10px); }
}
但這會使兩個框都介於-10和10px之間。 我想要的是相對於盒子的當前值。
因此,位於y:100px的box1將從90px動畫到110px,位於y:300px的box2將從290px動畫到310px
是否可以在CSS中執行此操作? 我希望每個框都沒有特定的動畫。 因為我可能有幾百個箱子。
jsfiddle: https ://jsfiddle.net/foreyez/1n1en8uk/
這表明在動畫時,兩個框都在同一位置...但是,如果是相對動畫,它們只會在當前位置上下浮動。
注意:請不要使用頂部/左側獲取相對位置,我正在專門尋找相對TRANSFORMS。 (如果您必須知道為什么我要在3d中為z軸執行此操作,因為已經使用了x,y)。
您可以將.item
元素的position
設置為relative
; 使用:nth-of-type()
偽選擇器將每個元素的top
屬性設置為初始位置,在該位置應相對於其.item
兄弟元素在20px
范圍內對元素進行動畫.item
。
.item { position: relative; background: red; animation: float 3s infinite ease-in-out; width: 100px; height: 100px; } .item:nth-of-type(1) { top: 100px; } .item:nth-of-type(2) { top: 300px; } @keyframes float { from, to { transform: translateY(-10px); } 50% { transform: translateY(10px); } }
<div class="item"> </div> <div class="item"> </div>
jsfiddle https://jsfiddle.net/1n1en8uk/3/
這是一個討厭的javascript解決方案(是的,我正在尋找一個CSS解決方案,這就是為什么我不會將其標記為答案)將動態關鍵幀注入到頁面中:
我想,只要少於100個盒子就可以工作。
https://jsfiddle.net/foreyez/6v7n4ro3/
function getTranslateY(obj)
{
var transformMatrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
var matrix = transformMatrix.replace(/[^0-9\-.,]/g, '').split(',');
var x = matrix[12] || matrix[4];//translate x
var y = matrix[13] || matrix[5];//translate y
return parseInt(y);
}
function insertAnimation(idx, yy)
{
var style1 = document.documentElement.appendChild(document.createElement("style")),
rule1 = "@keyframes float" + idx + " {\
from, to { transform: translateY("+ (yy-10) +"px); }\
50% { transform: translateY(" + (yy+10) + "px); }\
}";
style1.sheet.insertRule(rule1, 0);
}
$(".item").each(function(idx) {
var currentTranslateY = getTranslateY($(this));
insertAnimation(idx, currentTranslateY);
$(this).css('animation','float' + idx + ' 3s ease-in-out infinite');
});
注意:請不要使用頂部/左側獲取相對位置,我正在專門尋找相對TRANSFORMS。
您可以將html
調整為單個.item
元素,作為容器元素的子元素, transform
設置為translateY(100px)
, position
設置為absolute
; 利用css
:after
.item
元素:after
偽元素, .item
transform
設置為translateY(200px)
.float { transform: translateY(100px); position: absolute; } .item { animation: float 3s infinite ease-in-out; } .item, .item:after { display: block; position: relative; background: red; width: 100px; height: 100px; } .item:after { content: ""; transform: translateY(200px); } @keyframes float { from, to { transform: translateY(-10px); } 50% { transform: translateY(10px); } }
<div class="float"> <div class="item"> </div> </div>
jsfiddle https://jsfiddle.net/1n1en8uk/5/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.