循环进度条,通过JS控制百分比

时间:2015-07-06 14:27:44

标签: javascript css

首先,我尝试了这个进度条: http://jsfiddle.net/Aapn8/3410/ 我遇到了两个问题:

  1. 它弄乱了我的整个页面的CSS,因为进度条的元素没有id,我无法解决它

  2. 我无法通过javascript编辑百分比。

  3. 我需要一个循环进度条,我可以使用javascript控制每秒增加1%的百分比值

    我试图通过JS来设置进度条的百分比,但它没有工作

    var x=0;
    function update(y){
    document.getElementById("percent").setAttribute("data-percent",y)
    }
    
    setInterval(function(){ if (x < 10){x = x+1; update(x);} else {exit;} }, 1000);
    

1 个答案:

答案 0 :(得分:1)

试试这个,它不应该弄乱你的CSS。

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
    
if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
		percent = Math.min(Math.max(0, percent || 1), 1);
		ctx.beginPath();
		ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
		ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
		ctx.lineWidth = lineWidth
		ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

var handle = setInterval(function() {
  options.percent++;
  if(options.percent > 100) {
     clearInterval(handle);
     return;  
  }
  drawCircle('#555555', options.lineWidth, options.percent / 100);
  span.textContent = options.percent + '%';
}, 1000);
#graph div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
#graph canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
#graph span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

#graph input {
    width: 200px;
}
<div class="chart" id="graph" data-percent="1"></div>