问题描述
在this question之后,我想检测textarea
元素中的 Shift + Enter 键盘组合。考虑下面的代码块:
<!DOCTYPE html>
<html lang="en">
<head>
<Meta http-equiv="x-ua-compatible" content="ie=9" />
<title>test</title>
<HTA:APPLICATION APPLICATIONNAME="test" />
<style type="text/css">
textarea {
resize: none;
overflow: auto;
min-height: 50px;
max-height: 200px;
width: 100%;
}
</style>
<script language="javascript">
function auto_grow(element) {
element.style.height = "5px";
element.style.height = (element.scrollHeight) + "px";
}
</script>
<SCRIPT Language="VBScript">
Sub onkeydown_script()
If window.event.Keycode = 16 Then
MsgBox "You pressed the Shift key."
End If
End Sub
</SCRIPT>
</head>
<body>
<textarea oninput="auto_grow(this)" onkeydown="onkeydown_script()" onkeyup="onkeyup_script()" wrap="off"></textarea>
</body>
</html>
在onkeydown
事件中尝试检测 Shift 并失败了。如果您能帮助我知道检测 Shift + Enter 键盘组合的规范方法,我将不胜感激。
P.S.1。也对任何其他改进上述代码的建议表示赞赏。
P.S.2。解决方案不必在VBScript中。实际上,考虑到我更好理解的语言,JScript解决方案甚至更好。
P.S.3。我希望阅读这篇文章的人认为JScript和JavaScript是相似的但不是相同的语言。 Samwise HTA本身不是常规的HTML文档。这里没有标记HTML和JavaScript,因此请考虑这一点。
PS4。恕我直言,规范的解决方案应该是为键盘组合使用特定的Keycode
,或者应该有一个全局变量来指示的状态。 Shift ,或者如果不存在这样的预定义变量,我们可以自己定义。我尝试了this page和this page的shiftKey
属性,似乎都不起作用。
P.S.5。。令人惊讶的是,this page上的示例很好用。
P.S.6。。可悲的是,该帖子被标记为this one的重复,因此在这里我将解释为什么这个决定是不公正的:
更多信息here。
解决方法
如果您想要通过Shift + Enter键返回msgBox的代码,那么这是一种有效的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="x-ua-compatible" content="ie=9" />
<title>test</title>
<HTA:APPLICATION APPLICATIONNAME="test" />
<style type="text/css">
textarea {
resize: none;
overflow: auto;
min-height: 50px;
max-height: 200px;
width: 100%;
}
</style>
<script language="javascript">
function auto_grow(element) {
element.style.height = "5px";
element.style.height = (element.scrollHeight) + "px";
}
</script>
<SCRIPT Language="VBScript">
Sub onkeydown_script()
If window.event.Keycode = 16 and 13 Then
Msgbox "You pressed the Shift and Enter key."
End If
End Sub
</SCRIPT>
</head>
<body>
<textarea oninput="auto_grow(this)" onkeypress="onkeydown_script()" onkeyup="onkeydown_script()" wrap="off"></textarea>
</body>
</html>
,
好的,我想我找到了“规范”解决方案。我从this page修改了示例:
<html>
<head>
<title>shiftKey example</title>
<script type="text/javascript">
function showChar(e) {
alert(
"charCode: " + e.keyCode + "\n"
+ "Shift key pressed: " + e.shiftKey + "\n"
+ "Alt key pressed: " + e.altKey + "\n"
+ "Ctrl key pressed: " + e.ctrlKey + "\n"
);
}
</script>
</head>
<body onkeypress="showChar(event);">
<p>Press any character key,with or without holding down <br />
the <kbd>Shift</kbd> key.<br />
the <kbd>Alt</kbd> key.<br />
the <kbd>Ctrl</kbd> key.<br />
or a combination of those.</p>
</body>
</html>
点:
-
event.keyCode
区分大小写。 -
String.fromCharCode()
不存在。