JS基础回顾_事件种类
鼠标事件
let btn = document.getElementById('test_click')
// 与绑定顺序无关
btn.onclick = function () {
// log-async
console.log('click')
}
btn.onmousedown = function () {
// log-async
console.log('mousedown')
}
btn.onmouseup = function () {
// log-async
console.log('mouseup')
}
区分左右键
let btn = document.getElementById('test_click_which')
btn.onmousedown = function (e) {
if (e.button == 0) {
// log-async
console.log('left')
}
if (e.button == 1) {
// log-async
console.log('middle')
}
if (e.button == 2) {
// log-async
console.log('right')
}
}
键盘事件
document.onkeypress = function (e) {
// 适用于Shift + A
// log-async
console.log(String.fromCharCode(e.charCode))
}
Input 事件
请输入中文,避免和键盘事件冲突。
let input = document.getElementById('input')
input.onchange = function (e) {
// log-async
console.log(this.value)
}
滚轮事件
特殊作用:解决 IE 浏览器没有Fix
定位的问题
<!-- log -->
<style>
#scroll-container {
height: 200px;
overflow: scroll;
position: relative;
border: 1px solid black;
}
#fixed {
position: absolute;
width: 20px;
height: 20px;
top: 50%;
left: 50%;
margin-top: -10px;
margin-left: -10px;
background: red;
}
</style>
<div id="scroll-container">
借助 absolute定位 + 滚轮事件 来模拟fixed定位
<div id="fixed"></div>
<br><br><br><br><br>
<br><br><br><br><br>
<br><br><br><br><br>
<br><br><br><br><br>
<br><br><br><br><br>
</div>
<script>
let container = document.getElementById('scroll-container')
let fixed = document.getElementById('fixed')
let topInit = getComputedStyle(fixed, null).top.split('px')[0] * 1
container.style.marginTop = '-10px'
container.onscroll = function(e) {
// console.log(e.target === this)
let scrollTop = this.scrollTop
fixed.style.top = (topInit + scrollTop) + 'px'
}
</script>