用纯javascript突出一个可编辑的p标记

Focus out an editable p tag with pure javascript

本文关键字:一个 编辑 标记 javascript 用纯      更新时间:2023-09-26

我有以下html

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

和这个js

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

但是这个东西不工作。我如何聚焦与输入击中p标签。请不要使用jquery。谢谢:-)

你拼错了Listener,所以按键没有被抓住。您还需要防止像这样的按键

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>

尝试使用event.preventDefault(),创建input元素,width, height设置为0px, opacity设置为0。如果event.keyCode = 13,则用opacity0input上调用.focus()

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.net/ben86foo/10/

我认为正确的方法是.blur()

所以以下内容应该足够了:

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

您可以使用onbluronfocusout事件:

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

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