javascript - 使用 JQuery 倒数百分比

标签 javascript jquery html css

我有下面的代码,一旦将对象悬停在外面,我希望数字计数回到 0%。我也想不出我们如何让这个值在加载时再次消失。你能帮我解决这个问题吗?

提前致谢。

HTML

<div class="container">
<div class="fill" data-width="80%"></div>
</div>
<div class="container">
<div class="fill" data-width="50%"></div>
</div>

CSS

.container {
    position: relative;
    width: 300px;
    height: 30px;
    background-color: blue;
    margin: 10px auto;
}

.fill {
    height: 100%;
    width: 0;
    background-color: red;
    line-height: 30px;
    text-align: left;
    z-index: 1;
    text-align: right;
}

JQuery

$(function() {
   $('.container').hover( function(){
      var width=$(this).find(".fill").data('width');
      $(this).find(".fill").animate({ width: width }, {
        duration:800,
        step: function(now, fx) {
                $(this).html(Math.round(now) + '%');     
        }
    });
   },
   function(){
      $(this).find(".fill").animate({ "width": "0px" }, 800);
    });
});

jsFiddle http://jsfiddle.net/zp8pe069/

最佳答案

jsBin demo

CSS:将 overflow: hidden 设置为 .fill 以防止文本在动画结束后可见。

HTML:从数据属性中删除 %

JS 好了。所有你需要的:

$('.container').hover(function( e ){
  var $fill = $(this).find(".fill");
  var width = $fill.data('width');
  $fill.stop().animate({width: e.type=="mouseenter" ? width+"%" : "0%" }, {
    duration : 800,
    step : function(now) {
      $(this).html(Math.round(now) + '%') ;     
    }
  });
});

另请注意 .stop() 方法的使用,如果您歇斯底里地多次悬停 :) 它会阻止无尽的动画。

关于javascript - 使用 JQuery 倒数百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349790/

相关文章:

javascript - 如果加载失败,我如何在本地加载资源而不是 CDN?

javascript - React 状态下错误 "Cannot read property ' fname' of undefined"

javascript - 当设置对话框样式时,我应该使用什么作为选择器?

php - Magento + JQuery + Ajax - 如何仅重新加载自定义模块的一部分而不是整个 block ?

javascript - 选择选项以触发表格外观

javascript - html onClick 打开存储在 php 变量中的 url

javascript - 如何删除并重新添加在 div 中播放的 twilio 视频轨道?

javascript - 在 node.js 中检索经过 Twitter 验证的用户的推文

javascript - 使用不同的 URI anchor 重新加载页面

javascript - 使用 jQuery 将所有 HTML 内容从一个 div 复制到另一个