jQuery - 使浮动元素坚持另一个元素

Cha*_*had 5 css validation jquery

我正在使用这个 jQuery表单验证插件.它显示了一个很小的浮动div中的字段错误.

当显示错误div然后它对应的元素移出它的原始位置时出现问题.例如,如果在输入框I.show()上面是先前隐藏的元素,它将向下推送输入,但该输入的错误提示将保持不变.

如何使浮动div粘贴/跟随它的相应元素?

这个插件的代码在这里,示例在这里.

mag*_*tte 2

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

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

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

这是一个 .jsFiddle 向您展示我的意思:http ://jsfiddle.net/ysQCf/2/

CSS

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

p
{
    display: none;   
}
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)

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)
    });
});
Run Code Online (Sandbox Code Playgroud)