按钮
按钮很容易禁用,因为 disabled
是一个由浏览器处理的按钮属性:
<input type="submit" class="btn" value="My Input Submit" disabled/>
<input type="button" class="btn" value="My Input Button" disabled/>
<button class="btn" disabled>My Button</button>
要使用自定义 jQuery 函数禁用这些,您只需使用 fn.extend()
:
// Disable function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
// Disabled with:
$('input[type="submit"], input[type="button"], button').disable(true);
// Enabled with:
$('input[type="submit"], input[type="button"], button').disable(false);
JSFiddle disabled button and input demo .
否则你会使用 jQuery 的 prop()
方法:
$('button').prop('disabled', true);
$('button').prop('disabled', false);
anchor 标记
值得注意的是 disabled
不是 valid property用于 anchor 标签。因此,Bootstrap 在其 .btn
元素上使用以下样式:
.btn.disabled, .btn[disabled] {
cursor: default;
background-image: none;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
color: #333;
background-color: #E6E6E6;
}
注意 [disabled]
属性以及 .disabled
类是如何定位的。 .disabled
类是使 anchor 标记显示为禁用所需要的。
<a href="http://example.com" class="btn">My Link</a>
当然,这不会阻止链接在单击时起作用。以上链接将带我们到http://example.com .为了防止这种情况,我们可以添加一段简单的 jQuery 代码来定位带有 disabled
类的 anchor 标记来调用 event.preventDefault()
:
$('body').on('click', 'a.disabled', function(event) {
event.preventDefault();
});
我们可以使用 toggleClass()
切换 disabled
类:
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
var $this = $(this);
$this.toggleClass('disabled', state);
});
}
});
// Disabled with:
$('a').disable(true);
// Enabled with:
$('a').disable(false);
JSFiddle disabled link demo .
结合
然后我们可以扩展前面的禁用函数来检查我们尝试使用 is()
禁用的元素的类型.这样我们可以 toggleClass()
如果它不是 input
或 button
元素,或者切换 disabled
如果是属性:
// Extended disable function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
var $this = $(this);
if($this.is('input, button, textarea, select'))
this.disabled = state;
else
$this.toggleClass('disabled', state);
});
}
});
// Disabled on all:
$('input, button, a').disable(true);
// Enabled on all:
$('input, button, a').disable(false);
Full combined JSFiddle demo .
值得注意的是,上述函数也适用于所有输入类型。
我是一名优秀的程序员,十分优秀!