2014-09-19 162 views
0

我想通过每次10%我点击一个按钮,以增加一个进度的宽度:增加宽度10%?

<div id="#progressBar" style="width:50%"> </div> 

我想通过提高10%以上的进度条的宽度,当我点击一个按钮。

我试过,但它不工作:

$("#increaseButton").click(function() { 
    $("#progressBar").css("width",$("#div2increase").width + 10); 
}); 

请帮帮忙!

进度条的当前宽度可以是0%到100%之间的任何值。在增加10%的时候它是未知的

+0

CSS宽度以字符串形式返回,您不能将字符串添加到整数。因此,您必须获取CSS宽度的值,将其变成一个整数,然后添加它,然后设置该值。看看这里http://www.w3schools.com/jsref/jsref_parseint.asp – 2014-09-19 17:40:38

+0

当你定义一个没有百分比的宽度的CSS时,你必须在结尾添加'px'。 – Kuzgun 2014-09-19 17:54:35

回答

0

以下代码点击一个按钮会增加一个10%的条。当酒吧达到100%时,您无法再增加尺寸。

这是非常基本的一个,但我希望它可以帮助你开始。

http://jsfiddle.net/x8w2fbcg/6/

<div id="progressBar">bar</div> 
    <div id="progressBarFull"> &nbsp;</div> 
    <button id="btn" type="button">enlarge</button> 



    $("#btn").click(function() { 
     var curSize = $("#progressBar").width(); 
     var fullSize = $("#progressBarFull").width(); 
     if(curSize < 100) { 
      var increment = fullSize/ 10; 
     $("#progressBar").css('width', '+=' + increment); 
     } 
    }); 


    #progressBar { 
     position: fixed; 
     height: 20px; 
     width: 0px; 
     background-color: red; 
    z-index: 10;  
    } 
    #progressBarFull { 
     position: fixed; 
     height: 20px; 
     width: 100px; 
     background-color: gray;  
    } 
    #btn { 
      position: fixed; 
     top: 100px; 

    } 
0

对于你使用%,元素将继承%从它的父的宽度,所以你需要添加10%之前得到的进度的实际% width

$("#increaseButton").click(function() { 
 
    var $bar = $("#progressBar"); 
 
    var $barParent = $bar.parent(); 
 
    var perc = ~~($bar.width() * 100/$barParent.width()); 
 
    if(perc<100) $bar.css({ width : (perc+10) +"%" }); 
 
});
*{margin:0;} 
 
#progressBar{height:30px; background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="progressBar" style="width:50%"></div> 
 
<button id="increaseButton">INCREASE</button>

+0

有趣......什么~~代表什么?在此先感谢 – GibboK 2014-09-19 18:16:26

+1

@GibboK http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript – 2014-09-19 18:17:19