单击时清除 <p> 标记中的默认文本

Clear default text from <p> tag when clicked on

本文关键字:文本 默认 清除 单击      更新时间:2023-09-26

用这个小提琴:http://jsfiddle.net/2mw4c/12/

我希望能够清除<p>标签中的文本,然后开始键入。我遇到的问题是,当您单击时,<p>标签被清除,我无法输入它。

JavaScript:

$("p").on("mousedown", function(e){
    if($(this).text() === "Click"){
        $(this).text("").focus();
    }
});

.HTML:

<div class="content" contenteditable="true"><p>Click</p></div>

我需要能够做什么才能开始在标签中写入?

我不知道

你想实现什么,但是当我将contenteditable移动到p元素时,它对我有用。

我从您的评论中得到的印象是您希望在标记中保留当前结构。似乎由于p是空的,div正在崩溃。我已经更新了我的小提琴链接。

http://jsfiddle.net/nyaray/2UJRS/2/

小提琴演示

$("p").on("mousedown", function (e) {
    var that = $(this);
    var txt = that.text();
    if (txt === "Click") {
        height = that.css('height');
        that.css('height', height).text("").focus();
    } else if ((txt).length) {
        that.css('height', 'inherit');
    } else if (txt.length === 0) {
        that.css('height', height);
    }
});

您可以设置最小高度和宽度。您需要指定大小,否则,p-tag内将没有可点击的区域,因为in是内联元素。

http://jsfiddle.net/MrPolywhirl/WZg6H/

div.content>p {
    min-width: 1em;
    min-height: 1em;
    background: #EEF;
}

我认为您正在尝试<p>标签用作输入,因此请检查以下更改:

试试这个:

http://jsfiddle.net/2mw4c/22/