Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Replace keyCode in IE 11

We use this code for simulating Tab key with Enter key:

function EnterTab() {
    if (event.keyCode == 13) event.keyCode = 9;
    return false;
}

But in IE 11 keyCode is readonly and this code does not work. How I can solve this problem that my code run in IE 11?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

keyCode should be readonly in all modern browsers, simply because modifying it is hacky and unnecessary. Looking at the code you provided in your other question: keydown event does not fire correctly using jQuery trigger, we can imitate this functionality rather than attempt to return the altered event.

jQuery actually does let us modify the event object when it is passed in to a jQuery event handler. As you have tagged, we can therefore make use of this in our answer, passing the modifications into a trigger() called on the same element.

if (e.which === 13) {
    // Alter the normalised e.which property
    e.which = 9;

    // Alter the default properties for good measure
    e.charCode = 9;
    e.keyCode = 9;

    $(this).trigger(e);
    return false;
}

Note: I've used e.which rather than e.keyCode as jQuery normalises this across all browsers.

Here is a demo which shows this in action. If you press the Enter key when the input element is in focus, the event will be replaced with the Tab event:

var $input = $('input'),
    $p = $('p');

$input.on('keydown', function(e) {
    if (e.which == 13) {  
        $p.html($p.html() + 'Enter key intercepted, modifying 13 to 9.<br>');
                
        e.which = 9;
      
        e.charCode = 9;
        e.keyCode = 9;
      
        $(this).trigger(e);
      
        return false;
    }
  
    $p.html($p.html() + 'Key pressed: ' + e.keyCode + '<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<p></p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...