【问题标题】:How to disable the button with css如何使用css禁用按钮
【发布时间】:2018-01-02 03:07:28
【问题描述】:

我想在 Javascript 中使用它的 id 来禁用该链接。默认情况下它是不可见的,如下所示。当特定 id 来自后端时,我将启用链接。

HTML

<li id="viewroleId" style="display: none;">
    <a href="viewrole"><spring:message code="label.viewrole" /></a>
</li>

Javascript:-

if (key == 1) {
    var id = value;
    var div = document.getElementById(id);

    if(div != null){
        if (div.style.display == 'none' || div.style.display == '') {
            // Here it will display the link
            div.style.display = 'block';
        }
    }
}

在上面的 Javascript 代码中,我将显示链接,但我想显示和禁用链接。如何改为使用 CSS 禁用链接?

【问题讨论】:

  • 查看ngDisabled
  • 为什么不添加 disabled 作为属性? - 也作为建议 - 永远不要使用内联 css 或 js - 这是一种不好的做法,会导致代码难以维护
  • 如果我维护 ng-disabled,那么我需要为每个禁用的 href 提供不同的名称。现在 Id 来自 DB,所以我可以用它的 id 显示。
  • 你能做一个小提琴来让这个更清楚吗?如果 li 被隐藏,我看不出应该禁用链接的原因。
  • 在 IE 系列浏览器上,您可以使用元素的 disabled 属性,如 ' 链接内容`

标签: javascript html css angularjs


【解决方案1】:

首先,在css中创建一个这样的规则

.disabled {
    display: block !important; /* since you set the element's display to none inline,
                                  we need to use !important flag (which is pretty bad)
                                  to override the inline style */
    pointer-events: none; /* Disable an element interaction, so it will not respond any event */
    color: #ccc; /* Gray out the text color to signify being disabled */
}

现在在您的 javascript 中,只需提供您想要禁用类 disabled 的元素,就像这样

if (key == 1) {
    var id = value;
    var div = document.getElementById(id);

    if(div != null){
        if (div.className.indexOf('disabled') === -1) {
            // Your element will be visible, and disabled
            div.className += ' disabled';
        }
    }
}

【讨论】:

  • Dummy 这里的className是什么意思
  • className 是允许您操作每个HTMLElementclass 属性的属性
  • 我得到 div.className is ""(empty)
  • 你应该再看一遍我的代码,if 块if (div.className.indexOf('disabled') === -1) 检查div 指向的元素是否具有disabled 类,如果没有,则表示该元素是没有被禁用,所以我们添加类 disabled 来禁用它,我们检查它的类而不是它的 .style.display 就像你做的那样
  • 我正在禁用 Uncaught Natives
【解决方案2】:

如果您的应用基于 Angular 使用 ng-if,这是“自然方式”

<a ng-if="true" href="yourlink.html">Link<a/>
<a ng-if="!true" href="#">Link<a/>

最好尝试覆盖浏览器原生实现(链接...);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2021-01-27
    • 2020-10-05
    • 2011-03-12
    • 2014-04-21
    • 2013-08-02
    相关资源
    最近更新 更多