jQuery在Internet Explorer中隐藏/显示div无法正常工作

4
当我点击togglediv时,commentdiv必须可见或隐藏。以下代码在Firefox上可以运行但在Internet Explorer上不能:
$(document).ready(function(){
    $("#togglediv").click(function(){ 
        if( $("#commentdiv").is(":visible") ) {
            $("#commentdiv").hide("slow");
            $("#togglediv").text("show");
        } else {
            $("#commentdiv").show("slow");
            $("#togglediv").text("hide");
        }
    });
});
5个回答

6

在jQuery中有一个名为toggle的函数,它可以帮助你完成切换元素可见性的操作,无需手动检查元素是否可见:

$("#commentdiv").toggle("slow");

5
我会尝试:

我会尝试:

$(document).ready(function() {
  $("#togglediv").click(function() {
    // note: do this first because the :hidden test fails if you
    // do it after triggering a slow animation
    $("#togglediv").text($("#commentdiv").is(":hidden") ? "Hide" : "Sgiw");
    $("#commentdiv").toggle('slow');
  });
});

编辑:针对您的评论,这个例子在IE7/FF3中对我而言完美运行。注意:当使用慢速效果时,我确实不得不颠倒语句的顺序。有趣!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>Test</title>
  <style type="text/css">
    #togglediv { padding: 5px; background-color: yellow; }
    #commentdiv { padding: 5px; background-color: #CCC; height: 100px; }
  </style>
</head>
<body>
  <div id="togglediv">Hide</div>
  <div id="commentdiv">thanks for answer. but i have tried this code, it was okay. i want to use toggle("slow") effect. this effect is runing firefox, but not i.e. is it a bug?</div>
  <script type="text/javascript" src="jquery-1.3.1.js"></script>
  <script type="text/javascript">
  $(function() {
    $("#togglediv").click(function() {
      $("#togglediv").text($("#commentdiv").is(":hidden") ? "Hide" : "Show");
      $("#commentdiv").toggle('slow');
    });
  });
  </script>
</body>
</html>

谢谢您的回答。但是我已经尝试了这段代码,它可以正常运行。我想使用toggle("slow")效果。这个效果在Firefox中可以运行,但在IE中不行。这是一个bug吗? - ferixxx

2
您缺少一个闭合的}。
尝试:
  $(document).ready(function(){
             $("#togglediv").click(function(){
                if($("#commentdiv").is(":visible")){
                $("#commentdiv").hide("slow"); $("#togglediv").text("show");
                }
                else{
                $("#commentdiv").show("slow"); $("#togglediv").text("hide");
                }
            }
        });

1
我注意到一件有趣的事情,而且我认为cletus在上面已经提到过了,那就是如果你把“show”行和“text”行的顺序颠倒 - 它似乎开始工作了。我对此没有解释;知道背后正在发生什么事情会很好。

1
if(document.getElementById(ThisObj).style.display == 'none')
{
    document.getElementById(ThisObj).style.display = 'block';
}
else
{
    document.getElementById(ThisObj).style.display = 'none';
}

它运行正常:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接