展开并折叠按钮javascript

时间:2016-09-02 05:58:32

标签: javascript html

我正在努力扩展和折叠按钮。我这里有两张图片,重点应放在元素上。如果点击一次collapse,则另一次点击expand。我尝试过关注元素但.focus()无法正常工作。

HTML

<td  aria-expanded="false" name="td_tohide2" id="td_tohide2" style="padding:0px;" class="sectiontd" nowrap="true" >
  <img  role="button" aria-labelledby="hide_show" id="generalinfo_caretup" src="images/arrow_up_ps_oc.png" onkeypress="sh_keypress('td_tohide2','td_toshow2','generaltable',event)" onclick="sh('td_tohide2','td_toshow2','generaltable')" tabindex="0" />
</td>

<td aria-expanded="true" aria-labelledby="hide_show_" name="td_toshow2" id="td_toshow2" style="padding:0px;display:none" class="sectiontd" nowrap="true">
  <img role="button" id="generalinfo_caretdown" src="images/arrow_down_ps_oc.png" onkeypress="sh_keypress('td_toshow2','td_tohide2','generaltable',event)" onclick="sh('td_toshow2','td_tohide2','generaltable')" tabindex="0" />
</td>

Javascript

function sh_keypress(a,b,c,event){
  if( event.keyCode==13 || event.keyCode==32 || event.which==13 || event.which==32) {  
    if(document.getElementById(c).style.display=="none")
      document.getElementById(c).style.display = "";
    else
      document.getElementById(c).style.display = "none";
      document.getElementById(a).style.display="none"; //arrow images
      document.getElementById(b).style.display=""; //arrow images
      setTimeout("document.getElementById(b).focus()",1000);
      event.stopImmediatePropagation();  
    }   
  }
function sh(a,b,c)
  {

if(document.getElementById(c).style.display=="none")
  document.getElementById(c).style.display = "";
else
  document.getElementById(c).style.display = "none";


document.getElementById(a).style.display="none"; //arrow images
document.getElementById(b).style.display=""; //arrow images
}

任何人都可以说明我如何关注元素。

1 个答案:

答案 0 :(得分:1)

什么是sh?您尚未提供具有该名称的函数。假设提供了该函数并遵循相同的模式,则需要确保b的值传递到setTimeout

当前bsetTimeout的值很可能未定义。这是因为默认情况下在全局上下文中执行setTimeout。相反,你可以做这样的事情:

function sh_keypress(a,b,c,event) {
    if(event.keyCode==13 || event.keyCode==32 || event.which==13 || event.which==32) {  
        if(document.getElementById(c).style.display === 'none') {
            document.getElementById(c).style.display = "";
        } else {
            document.getElementById(c).style.display = "none";
            document.getElementById(a).style.display="none"; //arrow images
            document.getElementById(b).style.display=""; //arrow images
            // Use a function below to provide the value of `b` from `sh_keypress` scope
            setTimeout(function(){document.getElementById(b).focus()},1000);
            event.stopImmediatePropagation();
        }
    }
}