<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>键盘事件</title>
</head>
<body>
<div>
<h2>登录界面</h2>
<button class="login-btn">登录</button>
</div>
<script>
document.onkeyup = function(e){
e = e || window.event //事件对象
var keyCode = e.keyCode || e.which //兼容firfox2.0
// ctrl + enter keycode = 13
if(e.ctrlKey && keyCode == 13){
location.href = './main.html'
}
}
表单
var usernameInput = document.querySelector('input[name="username"]')
// usernameInput.oninput = function(){
// console.log(usernameInput.value);
// }
usernameInput.addEventListener('input',function(){
console.log('1>>> ',usernameInput.value);
})
usernameInput.addEventListener('input',function(){
console.log('2>>>',usernameInput.value);
})
* {
padding: 0;
margin: 0;
}
div {
height: 2000px;
width: 100%;
background-color: royalblue;
}
</style>
<!--
onscroll
load : 页面全部资源加载完毕
resize 页面大小事件
-->
<script>
window.onload = function () {
document.querySelector('div').innerHTML = '页面加载完成'
console.log('页面加载完成');
}
</script>
</head>
<body>
<div></div>
<script>
window.onscroll = function () {
console.log(document.documentElement.scrollTop);
}
window.onresize = function(){
console.log(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>
// 键盘按下
document.querySelector('input').onkeydown = function(event) {
console.log('虚拟键盘码:', event.keyCode)
console.log('是否按 ctrl:', event.ctrlKey)
console.log('是否按 alt:', event.altKey)
console.log('是否按 shift:', event.shiftKey)
}
控制盒子在文档中移动50px 通过方向键
<style>
.box {
width: 50px;
height: 50px;
background-color:
position: absolute;
top: 200px;
left: 300px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
// 在文档中按下键盘
document.onkeydown = function(event) {
console.log('keyCode:', event.keyCode)
// 获得键盘码
const code = event.keyCode
// 获得待移动的元素
const box = document.querySelector('.box')
// 获得当前元素的定位位置
const left = parseFloat(getComputedStyle(box).left)
const top = parseFloat(getComputedStyle(box).top)
// 根据所按方向键,重新计算定位
if (code === 37) { // 左
console.log('左')
box.style.left = left - 50 + 'px'
} else if (code === 39) { // 右
console.log('右')
box.style.left = left + 50 + 'px'
} else if (code === 38) { // 上
console.log('上')
box.style.top = top - 50 + 'px'
} else if (code === 40) { // 下
console.log('下')
box.style.top = top + 50 + 'px'
}
}
</script>
</body>