5

使用 jQuery UI 定位 div 时,我遇到了一个奇怪的问题。第一次调用该函数会将 div 放在预期的位置。随后的调用将 div 放置在窗口的右侧和底部越来越远。以下是我可以重现该问题的最少代码量。

<!DOCTYPE html>
<html>
<head>
    <title>jQuery UI Position Test </title>
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <style type="text/css">
        #header {
            height: 100px;
            background: orange;
        }

        #content {
            height: 300px;
            background: blue;
        }

        #message {
            width: 300px;
            background: yellow;
            position: absolute;
            display: none;
        }
    </style>
</head>

<body>
    <div id="header"></div>
    <div id="message">a message to the user</div>
    <div id="content">
        <input id="ShowMessageButton" type="button" value="Show Message" />
    </div>

    <script>
        $(document).ready(function () {
            $('#ShowMessageButton').bind("click", function () {
                $('#message').position({ my: "center top", at: "center bottom-12", of: "#header" });
                $('#message').fadeIn(800).delay(1000).fadeOut(1000);
            });
        });
    </script>
</body>
</html>

如果您第一次运行代码,这是我所期望的。

屏幕截图 1 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen1.png

第二次通话后

屏幕截图 2 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen2.png

第三次通话后

屏幕截图 3 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen3.png

请注意,您必须让淡入/淡出完成,否则问题不会发生。

4

2 回答 2

6

两件事情。First.bind()已被弃用,取而代之的是.on(). 其次,您需要将调用顺序更改为:

$('#ShowMessageButton').on("click", function () {
    $('#message').fadeIn(800).position({
        my: "center top",
        at: "center bottom-12",
        of: "#header"
    }).delay(1000).fadeOut(1000);
});

jsFiddle 示例

作为位置状态的文档,“注意:jQuery UI 不支持定位隐藏元素”。由于您尝试在隐藏元素上使用位置,因此您需要先使其可见。如果您没有使用原始代码的格式在此示例中完全淡出元素,您可以见证这一点。

于 2013-04-18T19:44:30.560 回答
1

尝试这个 -

$('#message').position({ my: "center top", at: "center bottom-12", of: "#header" });
$('#ShowMessageButton').bind("click", function () {
      $('#message').fadeIn(800).delay(1000).fadeOut(1000);
});

小提琴

于 2013-04-18T19:41:18.293 回答