使用纯javascript聚焦可编辑的p标签

时间:2015-10-27 03:54:16

标签: javascript html5 dom

我有以下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() ??;
    }
});

DEMO

但这件事不起作用。如何使用enter hit聚焦p标签。没有jquery请。谢谢: - )

4 个答案:

答案 0 :(得分:4)

你拼错了<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>
Listener

答案 1 :(得分:3)

我认为正确的方法是.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();            
    }
});

答案 2 :(得分:3)

尝试使用event.preventDefault(),创建input元素widthheight设置为0pxopacity设置为0 。如果event.keyCode等于13,请使用.focus() inputopacity上致电0

&#13;
&#13;
var p = document.querySelector('p');

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

jsfiddle https://jsfiddle.net/ben86foo/10/

答案 3 :(得分:0)

您可以使用AggregationBuilders// build the aggregation TermsBuilder agg = AggregationBuilders.terms("autocomplete") .field("autocomplete") .include("c.*") .order(Terms.Order.count(false)); // build the query SearchResponse searchResponse2 = newClient.prepareSearch(INDEX_NAME) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setSize(0) .setQuery(QueryBuilders.prefixQuery("autocomplete", "c")) .addAggregation(agg) .get(); 事件:

onblur

onfocusout