jQuery - 让一个浮动元素固定在另一个元素上

5
我正在使用 this jQuery 表单验证插件。它会在一个小的浮动 div 中显示字段错误,这很好。
问题出现在错误 div 显示时,对应的元素移动到原始位置之外。例如,如果在输入框上方 .show() 了一个之前隐藏的元素,它将推动输入框向下,但是该输入框的错误提示将保持在原位。
如何使浮动的 div 粘贴/跟随其对应的元素?
这个插件的代码在 here,示例在 here
1个回答

2

该插件使用绝对定位显示错误消息。

如果您添加了其他DOM元素并使输入字段相对于文档位置移动,则需要在修改DOM的脚本运行后手动重新定位所有验证<div>。

您可以尝试使用jQuery offset()方法http://api.jquery.com/offset/获取输入元素相对于文档的新位置,然后相应地调整验证<div>的上部和左部属性。

这是一个.jsFiddle示例,展示了我的意思: http://jsfiddle.net/ysQCf/2/

css

.errorMessage
{
    background-color: red; 
    position: absolute;
    left: 180px;
    top: 25px;
}

p
{
    display: none;   
}

html

<p id="hidden">if you display this the textbox will move down</p>
<input id="myInput" type="text" />
<div class="errorMessage">stick me to the div</div>
<br />
<input id="show" type="button" value="Show" />

javascript

$(function () {
    $("#show").click(function () {
        // Save the offset of the error against the input
        var offset = $(".errorMessage").offset();
        offset.left -= $("#myInput").offset().left;
        offset.top -= $("#myInput").offset().top;

        // Call your script to manipulate the DOM
        $("#hidden").show(); 

        // Move the error div to it's new position
        offset.left += $("#myInput").offset().left;
        offset.top += $("#myInput").offset().top;
        $(".errorMessage").offset(offset)
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接