How to disable all div content

2019-01-01 14:33发布

I was under the assumption that if I disabled a div, all content got disabled too.

However, the content is grayed but I can still interact with it.

Is there a way to do that? (disable a div and get all content disabled also)

24条回答
荒废的爱情
2楼-- · 2019-01-01 15:04

This is for the searchers,

The best I did is,

$('#myDiv *').attr("disabled", true);                   
$('#myDiv *').fadeTo('slow', .6);
查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 15:08

HTML input controls can be disabled using 'disabled' attribute as you know. Once 'disabled' attribute for an input control is set, event handlers associated with such control are not invoked.

You have to simulate above behavior for HTML elements that don't support 'disabled' attribute like div, if you wish.

If you have a div, and you want to support click or a key event on that div, then you have to do two things: 1) When you want to disable the div, set its disabled attribute as usual (just to comply with the convention) 2) In your div's click and/or key handlers, check if disabled attribute is set on the div. If it is, then just disregard the click or key event (e.g. just return immediately). If disabled attribute is not set, then do your div's click and/or key event logic.

Above steps are browser independent as well.

查看更多
余生请多指教
4楼-- · 2019-01-01 15:08
function disableItems(divSelector){
    var disableInputs = $(divSelector).find(":input").not("[disabled]");
    disableInputs.attr("data-reenable", true);
    disableInputs.attr("disabled", true);
}

function reEnableItems(divSelector){
    var reenableInputs = $(divSelector).find("[data-reenable]");
    reenableInputs.removeAttr("disabled");
    reenableInputs.removeAttr("data-reenable");
}
查看更多
何处买醉
5楼-- · 2019-01-01 15:09

You can use this simple CSS statement to disable events

#my-div {
    pointer-events:none;
}
查看更多
高级女魔头
6楼-- · 2019-01-01 15:09

As mentioned in comments, you are still able to access element by navigating between elements by using tab key. so I recommend this :

$("#mydiv")
  .css({"pointer-events" : "none" , "opacity" :  "0.4"})
  .attr("tabindex" , "-1");
查看更多
忆尘夕之涩
7楼-- · 2019-01-01 15:10

I just wanted to mention this extension method for enabling and disabling elements. I think it's a much cleaner way than adding and removing attributes directly.

Then you simply do:

$("div *").disable();
查看更多
登录 后发表回答