在CSS转换期间显示元素的大小值

Show size value of element during CSS transition

本文关键字:元素 显示 CSS 转换      更新时间:2024-06-24

当用户滚动到我页面上的某个元素时,我会添加一个类,它会启动一个宽度为0%的动画。例如,我从0%开始,然后上升到99%。当这个动画化时,有没有一种方法可以在HTML中显示这个宽度递增的页面,即这个值递增的<p>标记?CSS就是这样,当用户使用Javascript滚动到它时,我添加了class.active。

.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;
}
var div = document.getElementById("yourDiv"), parapgraph = document.getElementById("yourParagraph");  
setInterval(function(){
    paragraph.innerHTML = div.offsetWidth + "px";
}, 20);

这将段落内容设置为每20毫秒div的宽度。

最简单的方法是使用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 );
});