JQuery проблема с выпадающим меню

0

Проблемы:

  • Выпадающее menu(#sub-button) закрывается щелчком мыши, оно должно закрываться только при нажатии на видимую кнопку #button
  • Когда, например, я пытаюсь открыть второе раскрывающееся menu(#sub-button2) первое выпадающее меню должно немедленно закрыться при нажатии кнопки #button2

Код HTML:

<html>
<head>
<title>jquery ddm</title>
<style type="text/css">
#button {
    position:fixed;
    width:150px;
    height:40px;
    background-color:blue;
}
#sub-button {
    display: none;
    width:150px;
    height:30px;
    margin-top:41px;
    background-color:cyan;
}
#button2 {
    position:fixed;
    width:150px;
    height:40px;
background-color:orange;
}
#sub-button2 {
    display: none;
    width:150px;
    height:30px;
    margin-top:41px;
    background-color:aqua;
}
</style>
</head>
<body>
<div id="button">
        <div id="sub-button">6</div>
    </div>
<div style="clear:both"></div>
<div id="button2" style="margin-left:152px;">
        <div id="sub-button2">66</div>
    </div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/toggle.js"></script>

и js-код (toggle.js):

var myTimeout;
// show/hide sub-button menu
$( "#button" ).click(function() {
    $( "#sub-button" ).toggle();
});
// if mouse out of button and sub-button divs - close sub-button after 860ms
$( "#button" ).mouseout(function() {
    myTimeout = setTimeout( "jQuery('#sub-button').hide();",860 );
});
// if timer that are about to close sub-button is launched, stop it
// by hover button or sub-button divs
$( "#button" ).mouseover(function() {
    clearTimeout(myTimeout);
});

var myTimeout2;
$( "#button2" ).click(function() {
    $( "#sub-button2" ).toggle();
});
$( "#button2" ).mouseout(function() {
    myTimeout2 = setTimeout( "jQuery('#sub-button2').hide();",860 );
});
$( "#button2" ).mouseover(function() {
    clearTimeout(myTimeout2);
});

3 ответа

1
Лучший ответ

Первая проблема заключается в том, что подменю - это дочерний #button, поэтому событие click будет пузыриться до родителя, и код события #button click будет вызван.

Первая проблема, которую вы можете решить, тестируя исходную цель:

$( "#button" ).click(function(e) {
    if(e.target.id === 'button'){

        $( "#sub-button" ).toggle();

    }

});

Вторая проблема заключается в том, что нет, где в вашем коде вы закрываете первую кнопку при нажатии второй кнопки и наоборот

вы можете добавить:

$("#button").click(function (e) {
    if (e.target.id === 'button') {
        $("#sub-button2").hide();
        $("#sub-button").toggle();
    }

});

Хотя, если в дальнейшем у вас будет больше кнопок, этот JS можно и нужно убрать и сделать более эффективным, иначе вы рискуете, что код будет трудно поддерживать.

вот FIDDLE

1

просто измените свои js следующим образом:

var myTimeout;

// show/hide sub-button menu

$( "#button" ).click(function() {
    $("#sub-button2").hide();
    if (!$("#sub-button2").is(":visible")) $( "#sub-button" ).show();

});

// if mouse out of button and sub-button divs - close sub-button after 860ms

$( "#button" ).mouseout(function() {

myTimeout = setTimeout( "jQuery('#sub-button').hide();",860 );

});

// if timer that are about to close sub-button is launched, stop it

// by hover button or sub-button divs

$( "#button" ).mouseover(function() {

clearTimeout(myTimeout);
});

var myTimeout2;

$( "#button2" ).click(function() {
    if (!$("#sub-button2").is(":visible")) $( "#sub-button2" ).show();
    $("#sub-button").hide();
});

$( "#button2" ).mouseout(function() {

myTimeout2 = setTimeout( "jQuery('#sub-button2').hide();",860 );

});

$( "#button2" ).mouseover(function() {

clearTimeout(myTimeout2);

});
0

Если я правильно вас понимаю, вы хотите предотвратить появление пузырьков событий родителям, и если вы нажмете меню, скройте другого дочернего меню. Не нужно делать кучу "проверки", просто обрабатывайте события должным образом. Обратите внимание, где я комментирую "ДОБАВИТЬ" ниже

Попытайтесь привести пример к действию: http://jsfiddle.net/gP4CV/

var myTimeout;
// show/hide sub-button menu
$("#button").click(function () {
    $("#sub-button").toggle();
    $("#sub-button2").hide();// ADD hide other child
});
// ADD prevent event bubble to parent
$("#sub-button, #sub-button2").click(function (e) {
    e.stopPropagation();
});
// if mouse out of button and sub-button divs - close sub-button after 860ms
$("#button").mouseout(function () {
    myTimeout = setTimeout("jQuery('#sub-button').hide();", 860);
});
// if timer that are about to close sub-button is launched, stop it
// by hover button or sub-button divs
$("#button").mouseover(function () {
    clearTimeout(myTimeout);
});

var myTimeout2;
$("#button2").click(function () {
    $("#sub-button2").toggle();
    $("#sub-button").hide(); // ADD hide other child
});
$("#button2").mouseout(function () {
    myTimeout2 = setTimeout("jQuery('#sub-button2').hide();", 860);
});
$("#button2").mouseover(function () {
    clearTimeout(myTimeout2);
});

Ещё вопросы

Сообщество Overcoder
Наверх
Меню