简体   繁体   中英

Clear default text from <p> tag when clicked on

With this fiddle: http://jsfiddle.net/2mw4c/12/

I would like to be able to clear the text from the <p> tag, and begin to start typing. The problem I am having is that when you click, the <p> tag gets cleared, and I can't type in it.

JavaScript:

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

HTML:

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

What do I need to be able to do to start writing in the tag?

I don't know exactly what you're trying to achieve, but it worked for me when I moved the contenteditable to the p element.

The impression I'm getting from your comments is that you want to keep the current structure in your markup. It seems that the div is collapsing due to the p being empty. I've updated my fiddle link.

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

Fiddle DEMO

$("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);
    }
});

You can set a minimum height and width. You need to specify the size or else, there will be no clickable area inside the p-tag since in is an inline element.

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

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

I think the tag <p> you are trying is to use as input so please check the following change:

Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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