滑动div面板返回到div面板内的单击按钮

时间:2012-04-09 22:53:58

标签: jquery asp.net

我正在使用此代码从右侧滑动我的div(button_panel)按钮单击,一切正常,但当我单击div面板内的任何按钮时,面板将返回其原始位置。它不应该发生,因为click事件仅用于button_panel。知道为什么吗?

var sipPos = 0;
$(document).ready(function () {
    $("#button_panel").click(function (e) {
        e.preventDefault();
        $("#panel").animate({ right: sipPos }, 300, 'linear', function () {
            if (sipPos == 0) { sipPos = -150; }
            else { sipPos = 0; }
        });
    });
});

<div id="panel" style=" border-style: solid; border-color: #008000; background-color:#D5FFD5; width:150px; height:400px; right:-150px; top:142px; position:absolute" align="center" >
    <asp:ImageButton ID="button_panel" runat="server"  style=" background-image: url('images/ProgressBar1.jpg'); width:80px; height:30px; left:-83px;  margin-top:-12px; position:absolute; top:0px" Font-Bold="True" ImageUrl="~/images/green_left_arrow_104.jpg" />
    <asp:Label ID="Label6" runat="server" style="margin-top:5px"  Text="Timer" /><br />
    <asp:Button ID="Button1" runat="server" style="margin-top:5px" Text="AFK!" /><br />
    <asp:Button ID="Button2" runat="server" style="margin-top:5px" Text="REVIEW" /><br />
</div>

1 个答案:

答案 0 :(得分:0)

您的按钮会点击其所有父元素,包括面板。换句话说,事件通过DOM树冒泡。

您需要在按钮的处理程序中执行e.stopPropagation()

$(document).ready(function () {
    $("#button_panel").click(function (e) {
        e.preventDefault();

        $("#panel").animate({ right: sipPos }, 300, 'linear', function () {
            if (sipPos == 0) { sipPos = -150; }
            else { sipPos = 0; }
        });
    });

    $("#button_panel button").click(function (e) {
        e.stopPropagation();  // ADD THIS
    });
});

假设你实际上有button个元素。否则,如果您使用链接,请输入a。或者如果你们两个都这样做:

$("#button_panel button,a").click(function (e) {
    e.stopPropagation();
});

演示:http://jsfiddle.net/jtbowden/RDKn6/