禁用/启用按钮和链接的最简单方法是什么(jQuery + Bootstrap)

本文翻译自:What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Sometimes I use anchors styled as buttons and sometimes I just use buttons. 有时我使用锚作为按钮,有时我只使用按钮。 I want to disable specific clicky-things so that: 我想禁用特定的clicky-things,以便:

  • They look disabled 他们看起来残疾
  • They stop being clicked 他们不再被点击了

How can I do this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/18OSp/禁用-启用按钮和链接的最简单方法是什么-jQuery-Bootstrap


#2楼

@James Donnelly has supplied a comprehensive answer that relies on extending jQuery with a new function. @James Donnelly提供了一个全面的答案,它依赖于使用新功能扩展jQuery。 That is a great idea, so I am going to adapt his code so it works the way I need it to. 这是一个好主意,所以我将调整他的代码,使其按照我需要的方式工作。

Extending jQuery 扩展jQuery

$.fn.disable=-> setState $(@), true
$.fn.enable =-> setState $(@), false
$.fn.isDisabled =-> $(@).hasClass 'disabled'

setState=($el, state) ->
    $el.each ->
        $(@).prop('disabled', state) if $(@).is 'button, input'
        if state then $(@).addClass('disabled') else $(@).removeClass('disabled')

    $('body').on('click', 'a.disabled', -> false)

Usage 用法

$('.btn-stateful').disable()
$('#my-anchor').enable()

The code will process a single element or a list of elements. 代码将处理单个元素或元素列表。

Buttons and Inputs support the disabled property and, if set to true , they will look disabled (thanks to bootstrap) and will not fire when clicked. 按钮和输入支持disabled属性,如果设置为true ,它们将被禁用(感谢bootstrap)并且在单击时不会触发。

Anchors don't support the disabled property so instead we are going to rely on the .disabled class to make them look disabled (thanks to bootstrap again) and hook up a default click event that prevents the click by returning false (no need for preventDefault see here ). Anchor不支持disabled属性,所以我们将依赖.disabled类使它们看起来被禁用(再次感谢bootstrap)并挂钩一个默认的click事件,通过返回false来阻止点击(不需要preventDefault看到这里 )。

Note : You do not need to unhook this event when re-enabling anchors. 注意 :重新启用锚点时,无需取消挂钩此事件。 Simply removing the .disabled class does the trick. 简单地删除.disabled类就可以了。

Of course, this does not help if you have attached a custom click handler to the link, something that is very common when using bootstrap and jQuery. 当然,如果您已将自定义单击处理程序附加到链接,这将无济于事,这在使用bootstrap和jQuery时非常常见。 So to deal with this we are going tro use the isDisabled() extension to test for the .disabled class, like this: 因此,为了解决这个问题,我们将使用isDisabled()扩展来测试.disabled类,如下所示:

$('#my-anchor').click -> 
    return false if $(@).isDisabled()
    # do something useful

I hope that helps simplify things a bit. 我希望这有助于简化一些事情。


#3楼

Buttons 纽扣

Buttons are simple to disable as disabled is a button property which is handled by the browser: 按钮很容易禁用,因为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>

To disable these with a custom jQuery function, you'd simply make use of fn.extend() : 要使用自定义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 . JSFiddle禁用按钮和输入演示

Otherwise you'd make use of jQuery's prop() method: 否则你会使用jQuery的prop()方法:

$('button').prop('disabled', true);
$('button').prop('disabled', false);

Anchor Tags 锚标签

It's worth noting that disabled isn't a valid property for anchor tags. 值得注意的是, disabled不是锚标签的有效属性 For this reason, Bootstrap uses the following styling on its .btn elements: 因此,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;
}

Note how the [disabled] property is targeted as well as a .disabled class. 注意如何定位[disabled]属性以及.disabled类。 The .disabled class is what is needed to make an anchor tag appear disabled. .disabled类是使锚标记显示为禁用所需的类。

<a href="http://example.com" class="btn">My Link</a>

Of course, this will not prevent links from functioning when clicked. 当然,这不会阻止链接在单击时起作用。 The above link will take us to http://example.com . 以上链接将我们带到http://example.com To prevent this, we can add in a simple piece of jQuery code to target anchor tags with the disabled class to call event.preventDefault() : 为了防止这种情况,我们可以添加一个简单的jQuery代码来定位锚标签,并使用disabled类来调用event.preventDefault()

$('body').on('click', 'a.disabled', function(event) {
    event.preventDefault();
});

We can toggle the disabled class by using toggleClass() : 我们可以使用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 . JSFiddle禁用链接演示


Combined 综合

We can then extend the previous disable function made above to check the type of element we're attempting to disable using is() . 然后我们可以扩展上面的上一个禁用功能来检查我们尝试使用is()禁用的元素的类型。 This way we can toggleClass() if it isn't an input or button element, or toggle the disabled property if it is: 这样我们可以使用toggleClass()如果它不是inputbutton元素,或者如果是,则切换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 . 完整组合JSFiddle演示

It's worth further noting that the above function will also work on all input types. 值得进一步注意的是,上述函数也适用于所有输入类型。


#4楼

I can't think a simpler/easier way! 我想不出更简单/更简单的方法! ;-) ;-)


Using Anchor tags (Links) : 使用Anchor标签(链接):

<a href="#delete-modal" class="btn btn-danger" id="delete">Delete</a>

To enable the Anchor tag: 要启用Anchor标记:

 $('#delete').removeClass('disabled');
 $('#delete').attr("data-toggle", "modal");

在此输入图像描述


To disable the Anchor tag: 要禁用Anchor标记:

 $('#delete').addClass('disabled');
 $('#delete').removeAttr('data-toggle');

在此输入图像描述


#5楼

I know I'm late to the party, but to specifically answer the two questions: 我知道我迟到了,但要具体回答这两个问题:

"I just want to disable specific clicky-things so that: “我只是想禁用特定的点击事物,以便:

  • They stop clicking 他们停止点击
  • They look disabled 他们看起来残疾

How hard can this be?" 这有多难?“

They stop clicking 他们停止点击

1. For buttons like <button> or <input type="button"> you add the attribute: disabled . 1.对于<button><input type="button"> ,添加属性: disabled

<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>

2. For links, ANY link... actually, any HTML element, you can use CSS3 pointer events . 2.对于链接,任何链接......实际上,任何HTML元素,都可以使用CSS3 指针事件

.selector { pointer-events:none; }

Browser support for pointer events is awesome by today's state of the art (5/12/14). 浏览器对指针事件的支持在今天的最新技术水平(2014年12月5日)非常棒。 But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events . 但我们通常必须支持IE领域中的旧浏览器,因此IE10及以下版本不支持指针事件: http//caniuse.com/pointer-events So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers. 因此,使用其他人提到的JavaScript解决方案之一可能是传统浏览器的方法。

More info about pointer events: 有关指针事件的更多信息:

They look disabled 他们看起来残疾

Obviously this a CSS answer, so: 显然这是一个CSS答案,所以:

1. For buttons like <button> or <input type="button"> use the [attribute] selector: 1.对于<button><input type="button">使用[attribute]选择器:

button[disabled] { ... }

input[type=button][disabled] { ... }

-- -

Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/ 这是我在这里提到的东西的基本演示: http//jsfiddle.net/bXm5B/4/

Hope this helps. 希望这可以帮助。


#6楼

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. 请注意,如果您使用Bootstrap的JS按钮和“加载”状态,则会出现一个奇怪的问题。 I don't know why this happens, but here's how to fix it. 我不知道为什么会这样,但这是如何解决它。

Say you have a button and you set it to the loading state: 假设您有一个按钮并将其设置为加载状态:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (eg the button was a Save button, the loading state indicated an ongoing validation and the validation failed). 现在您想要将其从加载状态中取出,但也要将其禁用(例如,按钮是“保存”按钮,加载状态表示正在进行验证并且验证失败)。 This looks like reasonable Bootstrap JS: 这看起来像合理的Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. 不幸的是,这将重置按钮,但不会禁用它。 Apparently, button() performs some delayed task. 显然, button()执行一些延迟的任务。 So you'll also have to postpone your disabling: 所以你还必须推迟你的禁用:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot. 有点烦人,但这是我正在使用的模式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值