2017-06-22 160 views
0

有什麼方法可以在CSS中獲取目標對象的當前寬度嗎?CSS - currentwidth + px

我正在搞動畫,它會真的有用這樣的功能。

例子:

/*What has to be done atm*/ 

@keyframes identifier { 

    0%{width: 50px} 
    25%{width: 100px} 
    50%{width: 150px} 
    75%{width: 200px} 
    100%{width: 250px} 

} 

/*What I would like*/ 

@keyframes identifier { 

    0%{width: currentwidth +50px} 
    25%{width: currentwidth +50px} 
    50%{width: currentwidth +50px} 
    75%{width: currentwidth +50px} 
    100%{width: currentwidth +50px} 

} 

有了上次的代碼它實際上只是反覆多次,我想一個步驟,這可能嗎?

+0

你可以Ç在javascript中使用這些動畫或使用precentages –

+1

也許'calc(100%+ 50px)'? –

+1

你用'javascipt'標記了這個,但正在尋找一個css解決方案。你打開一個javascript解決方案嗎?怎麼樣一個CSS預處理器? –

回答

0

這是我第一次嘗試SCSS中的變量和循環,所以可能有更好的方法來做到這一點。 https://codepen.io/mcoker/pen/Zyydvw

HTML:

<div>foo</div> 

SCSS:

$width: 0; 
$percent: 0; 
$increment: 50; 

div { 
    animation: identifier 5s forwards; 
    background: red; 
} 

@keyframes identifier { 

    @while $percent < 101 { 
    #{$percent}% { 
     width: calc(#{$width}px + #{$increment}px); 
    } 
    $width: $width + $increment; 
    $percent: $percent + 25; 
    } 

} 

哪個編譯成

div { 
 
    animation: identifier 5s forwards; 
 
    background: red; 
 
} 
 

 
@keyframes identifier { 
 
    0% { 
 
    width: calc(0px + 50px); 
 
    } 
 
    25% { 
 
    width: calc(50px + 50px); 
 
    } 
 
    50% { 
 
    width: calc(100px + 50px); 
 
    } 
 
    75% { 
 
    width: calc(150px + 50px); 
 
    } 
 
    100% { 
 
    width: calc(200px + 50px); 
 
    } 
 
}
<div>foo</div>