2016-04-14 59 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); 
});