admin 管理员组

文章数量: 1086019

This is what I tried and obviously failed:

ed.on('keyup', function(e){
    console.log(e.keyCode)
    if(e.keyCode == 13 && !e.shiftKey){
        e.shiftKey = true;
        e.keyCode = 13;
        $(this).trigger(e);
    }
    else if (e.keyCode == 13 && e.shiftKey){
        e.shiftKey = false;
        e.keyCode = 13;
        $(this).trigger(e);
    }
}); 

Is there a way to do this cause based on what I seen I think I'm on the right track and most likely just not triggering it early or something similar.

Additionally, I tried using 'keypress' instead and had no luck with that.

This is what I tried and obviously failed:

ed.on('keyup', function(e){
    console.log(e.keyCode)
    if(e.keyCode == 13 && !e.shiftKey){
        e.shiftKey = true;
        e.keyCode = 13;
        $(this).trigger(e);
    }
    else if (e.keyCode == 13 && e.shiftKey){
        e.shiftKey = false;
        e.keyCode = 13;
        $(this).trigger(e);
    }
}); 

Is there a way to do this cause based on what I seen I think I'm on the right track and most likely just not triggering it early or something similar.

Additionally, I tried using 'keypress' instead and had no luck with that.

Share Improve this question edited Dec 19, 2019 at 14:54 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 24, 2017 at 19:49 David LionhardtDavid Lionhardt 852 silver badges9 bronze badges 3
  • Even if that worked, wouldn't that just be an infinite loop, as the shiftKey calls !shiftKey, which calls shiftKey, which calls !shiftKey... – Niet the Dark Absol Commented Aug 24, 2017 at 19:52
  • 2 shiftKey is a read-only property, so it cannot be changed: developer.mozilla/en-US/docs/Web/API/MouseEvent/shiftKey – Rick Hitchcock Commented Aug 24, 2017 at 20:02
  • Don't do that. Just a) preventDefault and insert a linebreak at the cursor position or (better and easier) b) just use a <textarea> instead of an <input>. – Bergi Commented Aug 24, 2017 at 20:12
Add a ment  | 

2 Answers 2

Reset to default 6
document.onkeydown = function onkeydown(e) {

    if (e.keyCode == 13 && e.shiftKey==false) {
        e.preventDefault(); 
        document.execCommand("insertLineBreak");    
    } 
}

When enter is pressed without shift, trigger keydown with enter and shift!

$('input').on('keydown', function(event) {
  if (event.keyCode == 13 && !event.shiftKey) {
    $(this).trigger(jQuery.Event("keydown", {
      keyCode: 13, // ENTER
      shiftKey: true
    }));
  } else if (event.keyCode == 13 && event.shiftKey) {
    console.log('shift + enter');
  }
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>

本文标签: jqueryIs there a way in JavaScript to change Enter to ShiftEnterStack Overflow