"开"切换按钮jQuery

时间:2015-11-18 20:57:47

标签: javascript jquery html css

如何停止"按钮" ("发送消息")切换菜单打开时关闭切换功能,以便关闭切换菜单的唯一方法是点击"发送"?



jQuery(document).ready(function() {
    $("#container").hide();

    $("#button").on('click', function() {
        $("#container").toggle();
        this.value = this.value == 'send message' ? 'contact' : 'send message';
    });

    $("#button2").on('click', function() {
        $("#container").toggle();
        $("#button").val('thank you');
    });
});

#container {
    height: 200px;
    width: 200px;
    position: relative;
    background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="contact" />
<br />
<div id="container">
    <input type="button" id="button2" value="send" />
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

Change

$("#button").on('click', function() {
$("#container").toggle();
this.value = this.value == 'send message' ? 'contact' : 'send message';
});

to

$("#button").on('click', function() {
if($("#container").is(":visible"))
    return false;

$("#container").toggle();
this.value = this.value == 'send message' ? 'contact' : 'send message';
});

This checks if the container is visible already, if it is then it stops the event handler from continuing.

You may need to set the container to display: none; in your css by default depending on if the container is technically visible when the button is clicked but obscured from view as jquery .is(":visible") isn't the most intuitive method in the world.

答案 1 :(得分:0)

You can just hide the initial button and then show it again when the user clicks send:

jQuery(document).ready(function () {  
    $("#container").hide();

    $("#button").on('click', function() {
        $("#container").toggle();
        $(this).hide();
    });

     $("#button2").on('click', function() {
        $("#container").toggle();
        $("#button").val('thank you');
        $("#button").show();
    });
});

JSFiddle