2016-04-14 62 views
1

當用戶滾動到我的頁面上的某個元素時,我將添加啓動它的寬度動畫的類。例如,我以0%的寬度開始,然後上升到99%。由於這種動畫有一種方法可以在HTML頁面中顯示此寬度增量,即<p>標記的值會遞增? CSS就是這樣,當用戶用Javascript滾動到它時,我添加了.active類。在CSS轉換期間顯示元素的大小值

.graph-horiz-bar__bar{ 
    background:$niagara; 
    top:0px; 
    position:absolute; 
    left:0px; 
    width:0; 
    height:100%; 
    transition: width 0.3s; 
} 
.graph-horiz-bar__bar.active{ 
    width:100%; 
    transition: width 0.3s; 
} 

回答

2
var div = document.getElementById("yourDiv"), parapgraph = document.getElementById("yourParagraph"); 
setInterval(function(){ 
    paragraph.innerHTML = div.offsetWidth + "px"; 
}, 20); 

這臺內容div的寬度每20毫秒的段落。

+0

'document.getElementById(「yourDiv」)。width' ???此外,每20ms查詢一個元素的DOM是一個非常糟糕的主意。 –

+0

再次...小心'Element.width'返回'undefined' ... 也有一段時間後停止那段時間會非常酷,你不覺得嗎? (不是說,至少在需要時啓動它會很好) –

+0

**不,它不是固定的**。這是錯誤的:'style.width'將返回'「」' –

1

最簡單的方法是動畫使用jQuery .animate()和閱讀從step:參數回調當前寬度(閱讀文檔)的元素寬度...

使用CSS3過渡:

var $bar = $("#bar"), 
 
    $currWidth = $("#currWidth"), 
 
    itv = null; 
 

 
$("#bar").on({ 
 
    // START COUNTING THE WIDTH 
 
    // I used a custom "start" event cause currently (2016) 
 
    // Event.transitionstart is implemented only in IE10+, Edge 
 
    start : function(){ 
 
    $(this).addClass("active"); 
 
    itv = setInterval(function(){ 
 
     $currWidth.text($bar[0].offsetWidth); 
 
    },10); 
 
    }, 
 
    // STOP COUNTING THE WIDTH 
 
    transitionend : function() { 
 
    clearInterval(itv); 
 
    $currWidth.text("INTERVAL STOPPED"); 
 
    } 
 
}); 
 

 

 
$("#start").on("click", function(){ // CLICK JUST FOR DEMO, 
 
    // You need to place this trigger inside your inViewport method 
 
    // when the element enters the viewport 
 
    $bar.trigger("start"); // <<---------------- 
 
});
#bar{ 
 
    height: 20px; 
 
    width:0; 
 
    background:red; 
 
    transition: 3s; 
 
} 
 
#bar.active{ 
 
    width:100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button id="start">ACTIVATE BAR</button><!-- TRIGGER BUTTON JUST FOR DEMO --> 
 

 
width <span id="currWidth">0</span> 
 
<div id="bar"></div>


transitionstart將所有主要的瀏覽器可以實現比代碼看起來很像:

var itv; 

$("#bar").on({ 
    transitionstart: function(){ 
    itv = setInterval(function(){ 
     console.log($bar[0].offsetWidth); 
    },10); 
    }, 
    transitionend : clearInterval(itv) 
}); 

$("#bar").addClass("active"); // place this call where needed 

也許有一天,在另一個星系像transitionstep一些事件可能是所有需要....

$("#bar").on("transitionstep", function(){ // :( 
    console.log(this.offsetWidth); 
});