如何在JQuery中创建通用切换功能?

时间:2019-07-18 09:20:46

标签: javascript jquery html asp.net-core razor

我有一个HTML辅助菜单,如下所示:

_Layout.cshtml

<div class="col nav-left h-100">
<p>Menu</p>
</div>

在我的 Site.js 中,我为切换设置了通用的JQuery函数:

var eventHandler = {
    addToggle: function addToggle(btnElem, openEvent, closeEvent) {
        const isClosedClass = 'this-is-closed';
        btnElem.click(function () {
            if ($(this).hasClass(isClosedClass)) {
                openEvent();
            } else {
                closeEvent();
            }
        });
    }
};

在我的 _Layout.cshtml 中,我这样调用此函数:

 <script>
        eventHandler.addToggle($(".btn-toggle-something"),
            function () {
                // Slide down
            },
            function () {
                // Slide up
            });

 </script>

现在,我陷入了如何编写div上实际切换逻辑的问题。

如何使用通用功能切换侧面菜单?

我看过的来源:

https://api.jquery.com/toggle/

How to toggle (hide / show) sidebar div using jQuery

1 个答案:

答案 0 :(得分:1)

.slideUp().slideDown().toggleClass()结合使用-请参见以下内容:

var eventHandler = {
    addToggle: function addToggle(btnElem, openEvent, closeEvent) {
        const isClosedClass = 'this-is-closed';
        btnElem.click(function () {
            if ($(this).hasClass(isClosedClass)) {
                openEvent();
            } else {
                closeEvent();
            }

            // Toggle `isClosedClass` for next time this is clicked.
            btnElem.toggleClass(isClosedClass);
        });
    }
};

// Bind slideDown/slideUp.
var leftNav = $('.nav-left');

eventHandler.addToggle($('.btn-toggle-something'),
    function () {
        leftNav.slideDown();
    },
    function () {
        leftNav.slideUp();
    }
);
body {
  margin: 0;
  padding: 0;
}

p {
  margin: 0;
}

.nav-left {
  background-color: lightskyblue;
  width: 200px;
  height: 400px;
}

.btn-toggle-something {
  cursor: pointer;
  position: fixed;
  top: 0;
  left: 250px;
  height: 50px;
  width: 50px;
  background-color: salmon;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col nav-left h-100">
  <p>Menu</p>
</div>

<div class="btn-toggle-something">Toggle</div>