隐藏元素时如何禁用`accesskey`?

时间:2016-10-25 05:56:19

标签: javascript jquery html hidden access-keys

请参阅以下代码:

$('div').click(function(){
   alert("Shortcut worked although element was hidden!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div hidden accesskey="1">
    Some things...
</div>

<p>
  Focus on me and then 
  </br>
  <b>press [Alt + 1] please!</b>
</p>

如何在元素隐藏时禁用accesskey

2 个答案:

答案 0 :(得分:1)

我认为没有办法禁用accesskey,您只需根据需要add / remove

if(!$('div').is(":visible"))
{
   $('div').removeAttr('accesskey');
}
else
{
   $('div').attr('accesskey', '1');
}

if(!$('div').is(":visible"))
{
  $('div').removeAttr('accesskey');
}
else
{
  $('div').attr('accesskey', '1');
}
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div hidden accesskey="1">
    Some things...
</div>

<p>
  Focus on me and then 
  </br>
  <b>press [Alt + 1] please!</b>
</p>

答案 1 :(得分:1)

您可以检查div事件中的hidden是否为click

$('div').click(function(event) {

  if (!$(this).is(':hidden')) {
    alert("Shortcut worked although element was hidden!");
  } else {
    event.preventDefault();
  }

});

https://jsfiddle.net/89b2jtmw/1/