如何在JavaScript中为锚标记创建“已禁用”

时间:2018-07-10 15:17:08

标签: javascript jquery

我希望禁用a元素,但似乎无法添加disabled: true。如何实现?

function x() {
  var audioBtn = $('<a/>', {
    'class': 'sound btn btn-primary'
  }).html('<i class="fa fa-volume-up"></i>');
  return audioBtn;
}

3 个答案:

答案 0 :(得分:0)

disabled元素没有<a>属性。但是,您仍然可以通过结合使用自定义数据属性和CSS样式来创建行为和样式均已禁用的链接。

HTML

<a data-disabled="true"></a>

jQuery

var btn = $('a');
btn.attr('data-disabled', true);

CSS

a[data-disabled="true"] {
    pointer-events: none;
    color: gray; 
    ...
}

答案 1 :(得分:0)

  • disabled属性适用于<input><textarea>等表单控件。

  • pointer-events: none对关键事件无效(请参阅链接#2)。

  • 通过其href值禁用链接。这是最好的方法,因为与pointer-events:none一样,它仍然可以注册以监听点击事件(请参阅链接#3和#4)。


演示

var lnx = document.links;

lnx[1].style.pointerEvents = "none";

lnx[2].href = "#/";

lnx[3].href = "#/";

function markText(e) {
  e.target.style.background = "rgba(255,200,0,0.6)";
  return false;
}
code,
kbd {
  color: red;
  text-decoration: underline;
}

li {
  line-height: 2;
}

a {
  text-decoration: none;
}
<ol>
  <li><a href='https://example.com'>This link is the control, it should function</a></li>

  <li><a href='https://example.com'>Set CSS property <code>pointer-events:none</code> is not completely effective since user can use keys like <kbd>TAB</kbd> and <kbd>ENTER</kbd></a></li>

  <li>

    <a href='#/'>Assigned <code>"#/"</code> for <code>href</code> value is very effective</a></li>

  <li>
    <a href='#/' onclick="var e=event; markText(e, this);">
      This link is link #3 with an attribute onclick event and a callback function</a>
  </li>
</ol>

答案 2 :(得分:0)

function x() {
  var audioBtn = $('<a class="sound btn btn-primary"/>').html('test<i class="fa fa-volume-up"></i>');
  return audioBtn;
}
$("body").append(x());
.sound {
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>