单击锚标记时如何打开和关闭div元素

时间:2013-12-22 13:51:44

标签: javascript jquery html

以下是我的html格式我想在点击leftbar标记时打开open-left div标记,并在点击leftbar标记时关闭open-left div标记。

    <div id="leftbar" class="snap-drawers">
            <div class="snap-drawer snap-drawer-left">
                <div>
                    <br />
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
                        <img src="assets/img/nloop-min.png" alt="" class="drawer-logo" />
                    </div>
                    <br />
                    <ul>
                        <li><a href="#"><i class="fa fa-home fa-1x"></i>&emsp;Home</a></li>
                        <li><a href="#"><i class="fa fa-dot-circle-o fa-1x"></i>&emsp;Tour</a></li>
                        <li><a href="#"><i class="fa fa-bullseye fa-1x"></i>&emsp;FAQ</a></li>
                        <li><a href="#"><i class="fa fa-magic fa-1x"></i>&emsp;About</a></li>
                        <li><a href="#"><i class="fa fa-comment-o fa-1x"></i>&emsp;Contact</a></li>
                    </ul>
                    <br />
                    <p>
                        &copy; 2013 - nLoop</p>
                </div>
            </div>
        </div>
        <div id="content" class="snap-content">
                <div id="sidebarmenu" class="col-lg-1 col-sm-1 col-xs-1 col-md-1">
                    <a href="#" id="open-left"></a>
                </div>
                <div id="rightpart" class="margingap">
            Right part
                </div>
        </div>

    <script type="text/javascript">
            var snapper = new Snap({
                element: document.getElementById('content'),
                disable: 'right'
            });
            $(document).ready(function () {
                var addEvent = function addEvent(element, eventName, func) {
    if (element.addEventListener) {
        return element.addEventListener(eventName, func, false);
    } else if (element.attachEvent) {
        return element.attachEvent("on" + eventName, func);
    }
};

addEvent(document.getElementById('open-left'), 'click', function () {

    snapper.open('left');

        var state = $(this).is('.open');
       if (state) {
            snapper.close('left');
        }
});

            });

        </script> 

3 个答案:

答案 0 :(得分:2)

在克隆锚标记时打开和关闭div元素:

$("#open-left").click(function(){
    $("#leftbar").toggle();
});

点击此处了解详情:.toggle() Documentation

代码说明:

我只是将点击事件附加到#open-left标记,然后我调用.toggle()上的#leftbar。这几乎记录了对象的当前状态,隐藏或显示的内容,然后根据状态调用特定的函数。

另外,请参阅此工作示例:fiddle

答案 1 :(得分:0)

您是否正在寻找jQuery的hide()show()之类的内容?或toggle()

答案 2 :(得分:0)

试试这个:

var isOpen = false;
$("#open-left").click(function(){
    if(isOpen){
       $("#leftbar").slideUp(); isOpen = false;}
    else{ $("#leftbar").slideDown(); isOpen = true; }
});