[英]How to make a generic toggle function in JQuery?
I have a sidemenu in HTML like this: 我在HTML中有一个这样的补充菜单:
_Layout.cshtml _Layout.cshtml
<div class="col nav-left h-100">
<p>Menu</p>
</div>
In my Site.js I have made a generic JQuery function for the toggle: 在我的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();
}
});
}
};
In my _Layout.cshtml I call this function like this: 在我的_Layout.cshtml中,我这样调用此函数:
<script>
eventHandler.addToggle($(".btn-toggle-something"),
function () {
// Slide down
},
function () {
// Slide up
});
</script>
Now I getting stuck how to write the logic for the actual toggle on a div. 现在,我陷入了如何编写div上实际切换逻辑的问题。
How can I toggle my side menu with a generic function? 如何使用通用功能切换侧面菜单?
Sources I looked: 我看过的资料:
https://api.jquery.com/toggle/ https://api.jquery.com/toggle/
How to toggle (hide / show) sidebar div using jQuery 如何使用jQuery切换(隐藏/显示)侧边栏div
.slideUp() and .slideDown() in combination with .toggleClass() will work - please see below: .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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.