0基础学Web—鼠标事件、键盘事件、表单事件、元素距离、元素位置
鼠标事件
双击
onclick ondblclick
鼠标悬浮与鼠标离开
onmouseover onm ouseout // 会发生冒泡
onmouseenter onm ouseleave // 不会发生冒泡
鼠标按下与弹起(监听左右键和滚轮)
onmouseup, onm ousedown
键盘事件
键盘按下
onkeydown
键盘长按
onkeypress
键盘弹起
onkeyup
表单事件
表单数据改变后,失去焦点时触发
onchange
失去焦点触发
onblur
获得焦点触发
onfocus
输入时触发
oninput
示例
<body>
用户名: <input type="text" name="user"> <br>
密码: <input type="password" name="pwd" onkeydown="login(event)"> <br>
<input type="button" value="登录" onclick="login(event)">
<script>
document.onmousedown = function (event) {
console.log('鼠标摁下', event.button)
}
document.onmouseup = function () {
console.log('鼠标弹起')
}
document.oncontextmenu = function () {
console.log('右键菜单')
}
document.onkeydown = function (event) {
console.log('键盘摁下', event.keyCode)
}
document.onkeypress = function (event) {
console.log('键盘一直摁', event.keyCode)
}
document.onkeyup = function (event) {
console.log('键盘弹起')
}
//回车触发
function login(event) {
console.log(event.keyCode)
if (event.keyCode == 13 || event.keyCode == undefined) {
alert('登录成功')
}
}
</script>
</body>
表单事件示例
<body>
<input type="text" class="search" placeholder="洗衣液">搜索
<script>
let _search = document.querySelector('.search')
_search.addEventListener('focus',()=>{
_search.placeholder = ''
})
_search.addEventListener('blur',()=>{
_search.placeholder = '洗衣液'
})
</script>
</body>
元素距离
<style>
.outter {
width: 200px;
height: 300px;
border: 5px solid black;
padding: 5px;
margin: 0 auto;
box-sizing: border-box;
overflow: auto;
}
</style>
<body>
<div class="outter">
<img src="images/tou01.jpg" alt="">
<img src="images/tou02.jpg" alt="">
<img src="images/tou03.jpg" alt="">
<img src="images/tou04.jpg" alt="">
</div>
<script>
let _outter = document.querySelector('.outter')
let _img = document.querySelectorAll('img')[1]
// 通过js设置的样式为行内样式,.style也只能获取行内样式
//可以通过js提供的先关距离属性获取
//clientWidth=内容宽度+padding宽高
console.log(_outter.clientWidth, _outter.clientHeight)
//offsetWidth=整个控件的宽度
console.log(_outter.offsetWidth, _outter.offsetHeight)
_outter.onscroll = function () {
//获取元素的滚动距离
// console.log(_outter.scrollTop,_outter.scrollLeft)
//获取元素距离父元素的顶部的高度,不受滚动条影响
console.log(_img.scrollHeight)
}
</script>
</body>
元素位置
如果祖先元素有定位,相对最近的定位的祖先元素的偏移量
如果祖先元素没有定位,相对于浏览器的偏移量
<style>
.outter {
width: 200px;
height: 200px;
background-color: #d7baba;
margin-left: 10px;
position: relative;
overflow: hidden;
}
.inner {
width: 100px;
height: 100px;
background-color: #bd0e0e;
margin: 50px auto;
}
</style>
<body>
<div class="outter">
<div class="inner"></div>
</div>
<script>
let _outter = document.querySelector('.outter')
let _inner = document.querySelector('.inner')
console.log(_inner.offsetLeft, _inner.offsetTop)
</script>
</body>
标签:Web,document,console,log,元素,键盘,事件,outter,event
From: https://blog.csdn.net/2201_75539182/article/details/144893540