2012-02-12 49 views
0

我试图在文本表单域上覆盖文本。当焦点事件发生时,文本应该出现在文本框的上方(并且存在错觉),并且留在那里直到用户实际键入一个字母。在焦点发生之前,已经有默认文本。动态表单域与JQuery覆盖

有一个类似/更简单的变化,其中框以默认值开始,默认值在焦点上消失,但这不是我在这种情况下要做的。

我遇到的问题是帮助文本在插入后出现在正确的位置,特别是动态设置顶部和左侧CSS属性。

我的onfocus功能:

TrueThis.OldValue = $('#MyField').val(); // Save the current value 
$('#MyField').val(''); // Empty the text box 

var OverlayHTML = '<div>This is helper text that goes on top.</div>' 


// Insert the Overlay and position the top and left to match the parent 
// PROBLEM:: The element is inserted, but is not positioned. 
// No top and left css attributes were assigned according to Firebug. 

$('#MyField').after(OverlayHTML).css({ 
    'top':$('#MyField').position.top, 
    'left':$('#MyField').position.left 
}); 

// Remove the overlay when a user starts typing. 
$('#MyField').next().keyup(function(){this.remove();}); 

我认为问题是,我没能抓住新的元素,或者可能直到整个函数完成它不会在DOM存在了吗?

回答

1

随着詹姆斯的建议,为KEYUP功能工作,我认为你需要将其绑定到实际的文本输入,并使用回调中的.next()函数删除叠加层。

// Remove the overlay when a user starts typing. 
$('#MyField').keyup(function(){$(this).next().remove();}); 

至于叠加的位置,它取决于父母对文本输入的内容。假设你有周围的输入相对定位的div:

<div class="positionRelative"> 
<input type="text" id="MyField" val=""/> 
</div> 

父DIV创建一个新的坐标系,使您可以设置叠加绝对定位:

var OverlayHTML = $('<div>This is helper text that goes on top.</div>').css({ 
    'position': 'absolute', 
    'top': 0, 
    'left': 0 
    }); 
1

可能还有其他的问题,但我注意到的第一件事情是,你不调用position方法:

$('#MyField').after(OverlayHTML).css({ 
    //Notice calls to position method. Returns object with top and left properties 
    'top':$('#MyField').position().top, 
    'left':$('#MyField').position().left 
}); 

编辑

还有一个明显的问题。您正尝试将CS​​S更改应用于#MyField,而不是新元素。最简单的解决方案可能是你把它添加到DOM之前,将CSS应用到新的元素:

var OverlayHTML = $('<div>This is helper text that goes on top.</div>').css({ 
    //Set CSS properties here 
});