[英]How do I toggle between two jquery functions
I have my dropdown menu script bellow: 我的下拉菜单脚本如下:
$(document).ready(function() {
$('.myMenu > li').bind('mouseover', openSubMenu);
$('.myMenu > li').bind('mouseout', closeSubMenu);
function openSubMenu() {
$(this).find('ul').css('visibility', 'visible');
};
function closeSubMenu() {
$(this).find('ul').css('visibility', 'hidden');
};
});
It shows dropdown menu when the mouse gets over. 鼠标悬停时显示下拉菜单。 I want to implement this on my responsive theme, so it has to be click. 我想在响应式主题上实现此功能,因此必须单击它。 I tried following code: 我尝试了以下代码:
$('.myMenu > li').toggle(openSubmenu, closeSubmenu);
Instead of 2 lines of .bind
. 而不是.bind
的2行。 But it wouldn't work, neither did .click
method helped. 但这是行不通的, .click
方法也.click
。 So how do I put two states/functions into .toggle
method ? 那么,如何将两个状态/函数放入.toggle
方法?
如果多数民众赞成在点击时发生,那么您可以使用一个点击处理程序,而改为切换CSS类:
$('.myMenu > li').bind('click', function(e) {$(this).toggleClass('hidden')});
Instead of using mouse events you can simply use hover also use show() and hide() instead of css hidden and don't worry it's cross-browser. 除了使用鼠标事件,您还可以简单地使用hover,也可以使用show()和hide()而不是隐藏的CSS,并且不用担心它是跨浏览器的。
$(document).ready(function() {
$('.myMenu').hover(function(){
$(this).find('ul').show();
}, function(){
$(this).find('ul').hide();
});
});
Use "on" to add event listeners for both mouseover and click. 使用“ on”为鼠标悬停和单击添加事件侦听器。
$(document).ready(function() {
$('.myMenu > li').on('mouseover click', openSubMenu);
$('.myMenu > li').on('mouseout', closeSubMenu);
function openSubMenu() {
$(this).find('ul').css('visibility', 'visible');
};
function closeSubMenu() {
$(this).find('ul').css('visibility', 'hidden');
};
});
I would create one handler for the class toggling, and bind it to all of the desired events like so: 我将为类切换创建一个处理程序,并将其绑定到所有所需的事件,如下所示:
CSS 的CSS
li.hidden ul {
visibility: hidden;
}
Javascript Java脚本
var toggleHiddenClass = function(){
$(this).toggleClass('hidden');
};
$('.myMenu > li').bind('mouseover mouseout click', toggleHiddenClass);
.toggle();
method accepts a boolean value true
to show and false
to hide. 方法接受一个布尔值true
来显示,而false
来隐藏。
So you can check the event type if event type is mouseover
then show the hidden ul
otherwise on mouseout
hide it. 因此,如果事件类型为mouseover
则可以检查事件类型,然后显示隐藏的ul
否则在mouseout
上将其隐藏。
Also as a side note you can use .on()
which is now standards of event binding in jquery. 另外,您可以使用.on()
,它现在是jquery中事件绑定的标准。
Try this: 尝试这个:
$('.myMenu > li').on('mouseover mouseout', function(e){
$(this).find('ul').toggle(e.type === "mouseover");
});
$('ul > li').on('mouseover mouseout', function(e) { $(this).find('ul').toggle(e.type === "mouseover"); });
ul ul { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>menu <ul> <li>sub menu</li> </ul> </li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.