HTML - 在用户输入时保留占位符 [英] HTML - Keep placeholder when user types

查看:103
本文介绍了HTML - 在用户输入时保留占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的输入:

 < input value =我的文本placeholder =Placeholder> 

当我在输入中输入内容时,占位符文本将消失,这很明显。



现在,我想要做的是当用户键入内容时,我希望占位符文本保留下来,以便您可以将占位符文本看作原始文本背后的背景文本:





编辑:我也希望能够使用JavaScript更改背景文本。 解决方案

很难想到这是一个很好的用例,因为它阻止了一些用户的输入。



一个简单的方法是使用



点击此处查看演示2.(与contenteditable)

I have an input like this:

<input value="My text" placeholder="Placeholder">

When I type something in the input the placeholder text will disappear, that's quite obvious.

Now, what I want to do is that I want the placeholder text to stay when the user types so you can see the placeholder text as a background text behind the original text:

EDIT: I also want to be able to change the background-text using JavaScript.

解决方案

Hard to think of a good usecase for such a behaviour, as it is blocking some of the users input.

An easy way would be to use input::after but this is not supported by any browser right now (thanks @JukkaK.Korpela).

But you can use a wrapper element and a data attribute, as follows:

<div class="placeholder" data-placeholder="my placeholder">
    <input value="My text" />  
</div>

With this css:

.placeholder
{
    position: relative;
}

.placeholder::after
{
    position: absolute;
    left: 5px;
    top: 3px;
    content: attr(data-placeholder);
    pointer-events: none;
    opacity: 0.6;
}

Resulting in:

Click here for jsFiddle demo.


Since you will have to do a lot of tweaking to make this look good, you may also consider using the wrapping <div> element as a input "look alike":

<div class="editable" data-placeholder="my placeholder">
    <input type="text" value="my Text" />
</div>

CSS:

.editable
{
    position: relative;
    border: 1px solid gray;
    padding: 3px;
    background-color: white;
    box-shadow: rgba(0,0,0,0.4) 2px 2px 2px inset;
}

.editable > input
{
    position: relative;
    z-index: 1;
    border: none;
    background-color: transparent;
    box-shadow: none;
    width: 100%;
}

.editable::after
{
    position: absolute;
    left: 4px;
    top: 5px;
    content: attr(data-placeholder);
    pointer-events: none;
    opacity: 0.5;
    z-index: 1;
}

Click here for the Demo 3. (with mocked <input />)

Click here for the Demo 2. (with contenteditable)

这篇关于HTML - 在用户输入时保留占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆