开发者

HTML <p> tag always steals cursor from input field

I want a <p> tag (or a label might be correct actually) to appear behind an input field so that I can show the active caret on the input field and then hide the absolutely positioned <p> tag when the user starts to typing.

you can see what the problem is here: http://jsfiddle.net/captainill/BG7Kx/

In the jsfiddle I've given the in开发者_运维百科put a value to illustrate the problem although in the solution there'd be no default text in the input.

relevant html:

<form name="tagset-form" id="tagset-form" action="" method="get">
            <p class="form-p-text">Add Set Name</p>
            <input id="tagset-name" class="text-input" type="text" value="some text that I would like to be above the <p> tag">
            <input id="tagsubmit" type="submit" value="" style="display:none;">                
        </form>

css:

input#tagset-name{
    width:100%;
    height:14px;
    padding:8px;
    line-height:15px;
    color:black;
    z-index: 2;
}

input:focus#tagset-name{
    color:white;
}
.form-p-text{
    z-index: 1;
    position:absolute;
    top:8px;
    left:180px;
    color:blue;
    font-weight:bold
}

EDIT: this jquery plugin does exactly what I want: http://o2v.net/blog/jquery-formlabels-plugin

It does so by creating a label, which when clicked, calls focus() on the input. It looks sharp too.


You could try the HTML5 placeholder attribute for <input>s, depending on how supported you want this to be.

http://diveintohtml5.ep.io/forms.html

Example:

<input type="text" placeholder="John Smith" name="full_name" />

Otherwise you can take a look at the onblur and onfocus events for <input>.


Problem explanation

The thing is that you set color:white on the input field when it has focus. That's why caret (as well as content value text) disappears when in focus. It's still there though. It's just not visible. If you'd type some text in and then double click input you'd see that edited text exists (selecting it will make it visible)

A possible non-HTML5 scripted approach

You probably want to set some init text and then reset it when input has focus. And afterwards to stay as user set it. This very simple jsFiddle shows how. It uses jQuery to acomplish desired behaviour. You could as well adopt it to set init text back to what it was when input stays empty. But my simple example doesn't do that. It's rather trivial to do that as well by binding blur event to input as well, that would check value and when empty remove the CSS class and set init text back in.

It does use some scripting though. I don't think this can be done purely by HTML+CSS. It would when input was a container element so you could use pseudo elements ::before or ::after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜