点击显示并隐藏菜单

时间:2011-09-05 14:34:14

标签: javascript jquery

为什么我可以在此代码中单击“项目信息”以显示文本,但无法再次单击它以隐藏文本。我有使用javascript的经验,并使代码混乱...任何帮助将非常感激。这是html代码:

<div  class:"descinner;" style="position:fixed; left:260px; top:595px;">
  <a href="javascript:void(0);" class="showDesc" style="display: inline; ">Project info</a>
  <div style="width: 500px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color:#fff; opacity: 0.9; position: fixed; margin-top: 10px; margin-left: 100px;  font-size: 14px; font-weight:bold; line-height: 125%; display: none; background-position: fixed; ">
    Exces eturio. Ipis eos autatus ad quia cum santo doluptio que dignatenis dipsam non cuptam, tectaer iosaperiam repudi imo quaerum resciet acercianis apedipsam dellendae nobis am raectotatur, cum expla enit placcup tasitium quias qui quia illaceribus quiates dolecte occusandit anduntibus doluptat.               
  </div>
</div>      

这是脚本:

<script type="text/javascript">
  var descShow = false;
  $('.showDesc').click(function(){
    $(this).hide();
    $(this).next().show();
    $('.descInner').css();                      
    descShow = true;
  });

  var ee;
  $('body').click(function(e){
    e = window.event || e; 
    ee = e;

    var node = e.srcElement || e.target;
    var $node = $(node);

    if(node=='javascript:void(0);'){
      return;
    }

    while ($node.html()!=null){
      if($node.hasClass('descInner')){
        $('.showDesc').next().hide();
        $('.showDesc').show();
        $('.descInner').css();
        descShow = false;
        return;
      }
      $node = $node.parent();
    };
});
</script>

1 个答案:

答案 0 :(得分:1)

如果你想要做的就是在点击链接时显示文字,然后将其隐藏在正文上,请使用类似的内容。可以在此处找到工作示例:http://jsfiddle.net/vb9NU/

$('.showDesc').click(function(e) {
    e.stopPropagation(); 
    $(this).hide().next().show(); // hides the link, shows the next div
    // $('.cssclass').show(); // if you want to make the div a css class, bit easier incase you change your markup (INSTEAD of .next().show() above)
});

$('body').click(function() { 
    $('.showDesc').show().next().hide(); // (if you make the div to show/hide based on a selector instead of next(), do a similar sort of thing as above
});

e.stopPropagation()停止点击链接'冒泡'到浏览器,认为它也是一个正文点击(这会导致它立即显示然后隐藏它)。

如果我不明白你的意思,我道歉。仅供参考,$node是div元素,也不是字符串。

尝试使用console.log(whateveryouwanttolog),例如console.log($node)在控制台中查看变量的值(在firebug或chrome / safari开发人员工具中)。它使事情变得更容易:)