将数字转换为100%

时间:2016-12-08 20:38:08

标签: javascript jquery

好吧,我正在尝试编写自己的音频播放器,已经有了持续时间和当前时间,现在我想用div宽度显示百分比的当前持续时间。我认为没有必要把我所有的球员代码放在这里,因为它只是一个简单的问题。让我这样解释一下,所以考虑一下:

  

持续时间 30

我希望以100%的百分比显示30,例如,如果持续时间 30 ,则显示div宽度为100%,如果 15 则显示50%,如下所示:

#duration {
height: 2px;
  background: red;
}
<div id="duration" style="width:100%">100%</div>

  

持续时间: 15(一半)

#duration {
height: 2px;
  background: red;
}
<div id="duration" style="width:50%">50%</div>

所以这是我的问题代码:

var current = $('#current').text(); //it return 15
var duration = $('#duration').text(); //it return 30

var currPrec = current / 100; // it return 0.15%
var durPrec = duration / 100; // it return 0.03%;

$('#length').text(currPrec + "%").animate({
width: currPrec
});
#length {
width: 0%;
  height: 2px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
currently: <a id="current">15</a>
<br/>
duration: <a id="duration">30</a>

<div id="length">0%</div>

但我希望将15%显示为50%,将20显示为75%,将30显示为100%,但我不知道!

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var current = $('#current').text(); //it return 15
var duration = $('#duration').text(); //it return 30

var currPrec = parseInt(current)*100.0/parseInt(duration);
$('#length').text(currPrec + "%").animate({
width: currPrec
});
&#13;
#length {
width: 0%;
  height: 2px;
  background: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
currently: <a id="current">15</a>
<br/>
duration: <a id="duration">30</a>

<div id="length">0%</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个var current = $('#current').text(); //it return 15 var duration = $('#duration').text(); //it return 30 var currPrec = 100 * (current/duration); // it return 50% var durPrec = duration / 100; // it return 0.03%; $('#length').text(currPrec + "%").animate({ width: currPrec });

&#13;
&#13;
#length {
width: 0%;
  height: 2px;
  background: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
currently: <a id="current">15</a>
<br/>
duration: <a id="duration">30</a>

<div id="length">0%</div>
&#13;
{{1}}
&#13;
&#13;
&#13;