JQuery隐藏/可见错误


JQuery Hidden / Visible Error

我是Jquery的新手。我想在我的网站上制作浮动菜单。我创建了div,它是id="item"

下面的代码在我的.php文件中,我也想在按下我的按钮后激活项目,该按钮是id="sidebarOpenfile"。

<div id="item" style="float:left">
<?php include("leftmenu.php"); ?>
</div> 

我的"sidebarOpenFile"代码在这里

  <button id="sidebarOpenfile" class="toolbarButton" title="Toggle OpenFile" tabindex="5" data-l10n-id="toggle_sidebar_openfile">
              <span data-l10n-id="toggle_openfile_label">Toggle OpenFile</span>
            </button>

另外,我的.php文件有viewer.js文件和.css文件。

我写了我的.js文件这个代码

document.getElementById('sidebarOpenfile').addEventListener('click',function() {
    alert("Its working"); // For sure whether event is working or not working,
 This code works and gets alert
$("#item").css('visibility','visible');
});

我也写了我的.css文件,这个代码

#item {
    position:absolute;
    top: 10px;
    width: 200px;
    bottom: 0px;
    background:orange;
    left:0px;
    visibility:hidden;
}

通常,按下按钮后,它会将项目的css可见性从隐藏更改为可见。但它似乎不起作用,也没有效果。

如有任何帮助,我将不胜感激。

点击时切换可见性非常简单。您不需要任何纯javascript,只需要一个(非常)小的jQuery:

<script>
  $('#sidebarOpenFile').click(function() {
  $('#item').toggle(); });
</script>

toggle()函数用于切换查询的#item的显示状态。

要隐藏或显示您可以使用:

 $('#sidebarOpenFile').click(function() {
   $('#item').show(); // or $('this').hide()
}

出于惯例的考虑,它应该封装在一个自调用的匿名函数中,比如:

(function(){
  $('#sidebarOpenFile').click(function() {
  $('#item').toggle(); });
})();

好。。。我会咬。。。第一个问题是:

document.getElementById('sidebarOpenfile').addEventListener()

对于初学者来说,在JQuery中只使用$("#sidebarOpenfile")引用它要容易得多。。。但我遇到的真正问题是,我在你的代码的其余部分找不到"sidebarOpenfile";您试图实现的div的id是"item",而不是"sidbarOpenfile"。

这很可能是你的问题。

另一种可能性是,php代码中实际上有正确的id,但您没有显示。

更新

好的。。。我的糟糕,睡眠不足。。你很紧张,身份证在那里,而且在正确的地方。

$('#sidebarOpenfile').click(function(){$("#item").css('visibility','visible')});

应该工作。。。但将仅显示该元素。

如果你希望它切换,你必须添加一点额外的:

$('#sidebarOpenfile').click(function()  
{
    if ($('#item').css('visibility')=='hidden')
    {
        $('#item').css('visibility', 'visible');
    } 
    else 
    {
        $('#item').css('visibility', 'hidden');
    }
 }); 

你能使用类似的东西吗:

$('#item').fadeToggle("fast", "linear"); //this will toggle the visibility back and forth and do it gradually

 $('#item').removeAttr('visibility');  //this will simply remove the visibility attribute thus making it visible by default

试试这个:

$('#item').on('click', function(e){
    $(this).css('display','none');
});

您可以使用这个简单的jQuery脚本切换元素的可见性属性:

$(document).ready(function () {
    var item = $('#item');
    $('#sidebarOpenfile').click(function() {
        if (item.css('visibility') == 'visible') {
            item.css('visibility', 'hidden');
        } else {
            item.css('visibility', 'visible');
        }
    });
});

jQuery fiddle与javascript fiddle