Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - Make a <br> instead of <div></div> by pressing Enter on a contenteditable

I've written a bit of code in my keyboard event handler to insert a <br> in response to the press of the Enter key:

event.preventDefault();
document.execCommand('InsertHTML', true, '<br>');

This only works if the cursor is between two Letters, if its on the end i need two <br>-Elements. Can i detect if i'm on the end of a Line? Or some other working idea for the Enter problem?

I also tried to catch the normal key-event (wothout the ctrl-Key pressed) and create a keyboard-event with JS where the Enter Key is pressed together with the ctrl. But this dosn't work…

It only has to Work in Webkit/Safari…

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to solve your problem, always keep a br element as the last element of your contenteditable div. This will ensure predictable behavior when injecting a br element vs. the browser default of injecting div elements. You can check the lastChild on keyup and mouseup to make sure it's a br element. Assuming you have a document like:

<div id="editable" contenteditable="true"></div>

You can use the following JavaScript (w/ jQuery 1.4+) to keep a br element as the last element and inject a br element instead of div div:

$(function(){

  $("#editable")

    // make sure br is always the lastChild of contenteditable
    .live("keyup mouseup", function(){
      if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
        this.appendChild(document.createChild("br"));
      }
    })

    // use br instead of div div
    .live("keypress", function(e){
      if (e.which == 13) {
        if (window.getSelection) {
          var selection = window.getSelection(),
              range = selection.getRangeAt(0),
              br = document.createElement("br");
          range.deleteContents();
          range.insertNode(br);
          range.setStartAfter(br);
          range.setEndAfter(br);
          range.collapse(false);
          selection.removeAllRanges();
          selection.addRange(range);
          return false;
        }
      }
    });

});

Tested on Apple OS X w/ Google Chrome 7, Mozilla Firefox 3.6, Apple Safari 5). Try using ierange to get this to work in Windows Internet Explorer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...