Html程序  |  39行  |  982 B

<body onload="setup()">
<p>cmd+b and cmd+i should generate a keydown event in contentEditable fields.  Also, calling
preventDefault() in the keydown event should cancel the text styling.</p>

<div contentEditable id="test" style="border: 1px solid; padding: 4px;">
This is some sample text.<br><br><br><br>
</div>
<div>
<input type="checkbox" id="disable"><label for="disable">preventDefault() in keydown</label>
</div>
<div id="log"></div>

<script>
function setup()
{
    var test = document.getElementById("test");
    test.addEventListener("keydown", keydown, false);

    var selection = window.getSelection();
    selection.setPosition(test, 0);
    selection.modify("extend", "forward", "sentence");
    test.focus();
}

function log(msg)
{
    var log = document.getElementById("log");
    log.innerHTML += "<br>" + msg;
}

function keydown(event)
{
    log("keydown");
    if (document.getElementById("disable").checked)
        event.preventDefault();
}
</script>
</body>