5
我使用的是this jQuery表單驗證插件。它顯示了一個很小的浮動div中的現場錯誤。jQuery - 將浮動元素粘貼到另一個元素
出現錯誤div時出現問題,然後與其對應的元素移出原始位置。例如,如果上面的輸入框是.show()是以前隱藏的元素,它會將輸入向下推,但輸入的錯誤提示將保留原位。
我該如何讓浮動div貼/跟隨它的相應元素?
我使用的是this jQuery表單驗證插件。它顯示了一個很小的浮動div中的現場錯誤。jQuery - 將浮動元素粘貼到另一個元素
出現錯誤div時出現問題,然後與其對應的元素移出原始位置。例如,如果上面的輸入框是.show()是以前隱藏的元素,它會將輸入向下推,但輸入的錯誤提示將保留原位。
我該如何讓浮動div貼/跟隨它的相應元素?
該插件對錯誤消息使用絕對定位。
如果您要添加其他DOM元素來移動相對於文檔的輸入字段位置,則需要在修改DOM運行的腳本之後手動重新定位所有驗證<div>'s。
您可以嘗試使用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)
});
});