Css 使用Jquery更改单击时的宽度
我有一个引导进度条,当宽度属性更改时,它会更改当前进度。我想更改这个宽度属性,当用户打开它时增加10%,当用户关闭它时减少10%Css 使用Jquery更改单击时的宽度,css,twitter-bootstrap,jquery,Css,Twitter Bootstrap,Jquery,我有一个引导进度条,当宽度属性更改时,它会更改当前进度。我想更改这个宽度属性,当用户打开它时增加10%,当用户关闭它时减少10% 这是我的代码: <div class="progress progress-danger progress-striped active"> <div class="bar" style="width:30%"></div> </div> <a id="updateit">Click to
这是我的代码:
<div class="progress progress-danger progress-striped active">
<div class="bar" style="width:30%"></div>
</div>
<a id="updateit">Click to change the progress</a>
提前感谢!:) 您不能添加百分比(我相信),因此我使用
.progress
的宽度对其进行了转换
0.1=10%
$(function(){
$("#updateit").toggle(
function(){
$('.bar').css("width", '+=' + (0.1 * $('.progress').width()));
return false;
},
function(){
$('.bar').css("width", '-=' + (0.1 * $('.progress').width()));
return false;
});
});
我注意到你的代码有一些问题 首先,确保你的锚上有一个
href
。即使没有使用它,它也是正确的HTML(将return false;
添加到JavaScript中,使其不跟随链接)。我的浏览器根本无法识别该链接,因为它没有href
接下来,您希望用户单击链接,然后它切换宽度,对吗?然后需要click()
事件
在那之后,我想到的是:
jQuery
var isOn = true;
$(function(){
$("#updateit").click(function(){
console.log(isOn);
if ( isOn ){
isOn = false;
$('.bar').css("width", '10%');
} else {
isOn = true;
$('.bar').css("width", '20%');
}
return false;
});
});
HTML
<div class="progress progress-danger progress-striped active">
<div class="bar"></div>
</div>
<a href="#" id="updateit">Click to change the progress</a>
另一个答案上的示例是可以的,但是.bar最终会有一个固定的像素值。如果仍要将值设置为%(如果父对象更改了其宽度,.bar也将更改为%values),则可以尝试此操作:
<div class="progress progress-danger progress-striped active">
<div class="bar"></div>
</div>
<a href="#" id="updateit">Click to change the progress</a>
.bar{
width:20%;
height:20px;
background:#600;
}
$(function(){
var $bar = $(".bar");
$("#updateit").toggle(function(){
$bar.css("width", 100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) +10 + '%');
},
function(){
$bar.css("width", 100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) -10 + '%');
});
});