Html 如何为类似于文本字段的 DIV 创建“占位符”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16941360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:06:33  来源:igfitidea点击:

How to create a "placeholder" for DIV that act like textfield?

htmlplaceholder

提问by user2399158

Div don't have a placeholder attribute

Div 没有占位符属性

<div id="editable" contentEditable="true"></div>

I want <Please your enter your Name>to show in DIV when the User backspace the whole text in the DIV, or no text on inside, How can I do it?

<Please your enter your Name>当用户退格 DIV 中的整个文本时,我想在 DIV 中显示,或者里面没有文本,我该怎么做?

回答by mrmoje

Here is a pure CSS only solution:-

这是一个纯 CSS 解决方案:-

<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
    [contentEditable=true]:empty:not(:focus):before{
        content:attr(data-ph)
    }
</style>

Here, we basically select all contentEditable<divs>that are empty & blurred. We then create a pseudo element before the CSS selection (the editable div) and fix our placeholder text (specified the data-phattribute) as its content.

If you are targeting old school CSS2 browsers, change all occurrences of data-phto title
Correction.......the :emptyselector is not supported in IE version 8 and earlier.

在这里,我们基本上选择所有contentEditable<divs>空的和模糊的。然后我们在 CSS 选择(可编辑 div)之前创建一个伪元素,并将占位符文本(指定data-ph属性)固定为其内容。

如果您的目标是旧式 CSS2 浏览器,data-phtitle
请将所有出现的 更改更正....... :emptyIE 8 及更早版本不支持选择器。

回答by MD Furkanul Islam

You can try this one !

你可以试试这个!

html:

html:

<div contentEditable=true data-text="Enter name here"></div>

css:

css:

[contentEditable=true]:empty:not(:focus):before{
content:attr(data-text) }

check it out (demo)

检查出来(演示)

回答by acudars

in HTML

在 HTML 中

<div id="editable" contenteditable="true">
    <p>Please your enter your Name</p>
</div>

in JavaScript

在 JavaScript 中

jQuery.fn.selectText = function(){
    var doc = document;
    var element = this[0];
    console.log(this, element);
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

$("#editable").click(function() {
    $("#editable").selectText();
});

jsFiddle

js小提琴