最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Focus out an editable p tag with pure javascript - Stack Overflow

programmeradmin3浏览0评论

I have following html

<p contenteditable>The greatest p tag of all p tags all the time</p>

and this js

var p = document.querySelector('p');

p.addEventListner('keypress', function (e) {
    if (e.which === 13) {
        //this.focusout() ??;
    }
});

DEMO

But this thing doesn't work. How do i focusout the p tag with enter hit. No jquery Please. Thanks :-)

I have following html

<p contenteditable>The greatest p tag of all p tags all the time</p>

and this js

var p = document.querySelector('p');

p.addEventListner('keypress', function (e) {
    if (e.which === 13) {
        //this.focusout() ??;
    }
});

DEMO

But this thing doesn't work. How do i focusout the p tag with enter hit. No jquery Please. Thanks :-)

Share Improve this question asked Oct 27, 2015 at 3:54 It worked yesterday.It worked yesterday. 4,62711 gold badges50 silver badges84 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You misspelled Listener so the keypress wasn't being caught. You'll also want to prevent keypress like this

var p = document.querySelector('p');
p.addEventListener('keypress', function (e) {
    if (e.which === 13) {
        this.blur();
        e.preventDefault();
    }
});
<p contenteditable>The greatest p tag of all p tags all the time</p>

Try using event.preventDefault() , creating input element having width , height set to 0px , opacity set to 0 . If event.keyCode equals 13 , call .focus() on input with opacity 0

var p = document.querySelector('p');

p.onkeypress = function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    document.getElementById("focus").focus();
  }
};
#focus {
  width: 0;
  height: 0;
  opacity: 0;
}
<p contentEditable>The greatest p tag of all p tags all the time</p>
<input id="focus" />

jsfiddle https://jsfiddle/ben86foo/10/

I think the correct method for this is .blur()

So the following should suffice:

var p = document.querySelector('p');

p.addEventListener('keypress', function (e) { // you spelt addEventListener wrongly
    if (e.which === 13) {
        e.preventDefault();// to prevent the default enter functionality
        this.blur();            
    }
});

You can use the onblur or onfocusout event:

<p onblur="myFunction()" contenteditable>
    The greatest p tag of all p tags all the time
</p>

or

<p onfocusout="myFunction()" contenteditable>
    The greatest p tag of all p tags all the time
</p>
发布评论

评论列表(0)

  1. 暂无评论