简体   繁体   English

如何在文本字段中放置标签?

[英]How can I position a label inside its textfield?

I have many textfields that show instruction text within the textbox (how the default value would look). 我有很多文本字段在文本框中显示指令文本(默认值的外观)。 On focus the color of the text becomes lighter, but doesn't go away until text is entered. 在焦点上,文本的颜色变浅,但在输入文本之前不会消失。 When text is erased, the label returns. 删除文本时,标签返回。 It's pretty slick. 这很漂亮。 A default value doesn't cut it, because these go away onfocus. 默认值不会削减它,因为这些会消失。

I have it working, but the code is complicated because it relies on negative margins that correspond to the individual widths of the textfields. 我有它的工作,但代码很复杂,因为它依赖于与文本字段的各个宽度相对应的负边距。 I want a dynamic solution where the label for its textfield is positioned correctly automatically, probably using a script. 我想要一个动态解决方案,其文本字段的标签可以自动正确定位,可能使用脚本。

Any help would be greatly appreciated. 任何帮助将不胜感激。 But I am not looking for default values as a solution. 但我不是在寻找默认值作为解决方案。

Thanks. 谢谢。

Mike 麦克风

Edited to be more precise. 编辑得更精确。

Edited again to provide some simple code that illustrates the effect I am after: 再次编辑提供一些简单的代码,说明我的效果:

<input style="position: relative; width: 150px; font-size: 10px; font-family: Verdana, sans-serif; " type="text" name="name" id="name"
onfocus="javascript: document.getElementById('nameLabel').style.color='#BEBEBE';"
onkeypress="javascript: if (event.keyCode!=9) {document.getElementById('nameLabel').innerHTML='&nbsp;';}"
onkeyup="javascript: if (this.value=='') document.getElementById('nameLabel').innerHTML='Your&#160;Name';"
onblur="javascript: if (this.value=='') {document.getElementById('nameLabel').style.color='#7e7e7e'; document.getElementById('nameLabel').innerHTML='Your&#160;Name';}"/>
<label id="nameLabel" for="name" style="position: relative; margin-left: -150px; font-size: 10px; font-family: Verdana, sans-serif;">Your Name</label>

I would have taken a different approach (It's not entirely my idea, but i can't find the source for credit): 我会采取不同的方法(这不完全是我的想法,但我找不到信用来源):

1st - Use html5 "placeholder" property. 1st - 使用html5“占位符”属性。

2nd - Use Modernizr.js to detect support of placeholders in the browser and a simple jQuery script to add support to browsers that doesn't support it. 第二步 - 使用Modernizr.js检测浏览器中占位符的支持,以及一个简单的jQuery脚本,以便为不支持它的浏览器添加支持。

So, the html will look something like that: 所以,html看起来像这样:

<input type="text" class="placeholder" placeholder="Help Text" />
<textarea class="placeholder" placeholder="Another help text"></textarea>

The css: css:

.placeholder{color:#ccc;}

And the javascript: 和javascript:

/* Set placeholder for browsers that don't support HTML5 <input placeholder='text'>
 * Depends on Modernizr v1.5
 */
if (!Modernizr.input.placeholder){
    $('input[placeholder], textarea[placeholder]')
        .focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        })
        .blur(function() {
            var input = $(this);
            if (input.val() == '') {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }

        })
        //Run once on load
        .blur();

    // Clear all 'placeholders' on submit
    $('input[placeholder], textarea[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        });
    });
}

Do you mean like this ? 你的意思是这样的吗? But instead of 'required' it would have the label? 但不是“必需”它会有标签吗?

I used a jQuery solution where I set the value of the input to 'required'. 我使用了jQuery解决方案,我将输入值设置为'required'。 The input has a class of gray so the default text is lighter. 输入具有灰色类,因此默认文本较浅。


Edit after comment 评论后编辑

Instead of using focus, you can change the input values on keydown and keyup. 您可以在keydown和keyup上更改输入值,而不是使用焦点。

$('.required_input').keydown(function()
{
    if (this.value == 'required')
    {
        $(this).val('').removeClass('gray');
    }
} );

$('.required_input').keyup(function()
{
    if (this.value == '')
    {
        $(this).val('required').addClass('gray');
    }
} );

$('.required_input').blur(function()
{
    if (this.value == '')
    {
        $(this).val('required').addClass('gray');
    }
} );

What you are asking here is probably what is called textbox watermark. 你在这里问的可能就是所谓的文本框水印。

For this, you usually don't use a label (control) inside a textfield. 为此,您通常不在文本字段内使用标签(控件)。 Instead you replace the content of the textfield when the real content of the text field is empty with some text using certain CSS property and then remove it once you blur out (w/ additional check to see if the text inside the textbox itself is the same as the watermark text. If it is, blank the field again.) 相反,当文本字段的真实内容为空时,使用某些CSS属性将某些文本替换为文本字段的内容,然后在模糊后将其删除(附加检查以查看文本框内部的文本是否相同)作为水印文本。如果是,则再次将该字段留空。)

Try this . 试试这个 It's pretty simple implementation of this using jquery and css. 使用jquery和css实现这个非常简单。

Here's one that I borrowed from somewhere: 这是我从某个地方借来的:

$(function() {

    // Give the textbox a watermark
    swapValues = [];
    $('.your_input_class').each(function(i){
        $(this).val("Please enter xyz");
        swapValues[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValues[i]) {
                $(this).val("").css("color", "#333");
            }
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]).css("color", "#ccc");
            }
        });
    });

});

And then for your input box: 然后为您的输入框:

<input class="your_input_class" type="text" value="" />

It remembers the value that is stored in it when the page loads (well, I'm setting mine directly in the JS) and it also changes the color when it's focused/not focused. 它会记住页面加载时存储在其中的值(好吧,我直接在JS中设置我的),它也会在聚焦/不聚焦时改变颜色。

<script type="text/javascript">
    window.onload = function(){
        inputs = document.getElementsByTagName("input");
        for(i = 0; i < inputs.length;i++){
            var feild = inputs[i];
            if(feild.type == "text"){
                var label = document.getElementById(feild.id + "Label");
                label.style.left = "-" + feild.clientWidth;
            }
        }
    }
</script>

This bit of script should do what you wanted 这段脚本应该做你想要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM