鼠標(biāo)事件
document.onclick = function(ev) {
var oEvent = ev || event; //ie下ev不存在菇怀,firefox默認(rèn)傳一個(gè)ev
oEvent.clientX; //鼠標(biāo)點(diǎn)擊時(shí)的位置
}
事件冒泡
//取消事件冒泡
oBtn.onclick = function(ev) {
var oEvent = ev || event;
oEvent.cancelBubble = true;
}
控件隨著鼠標(biāo)移動(dòng)
document.onmousemove = function(ev) {
var oEvent = ev || event;
//clientX和clientY代表的是可視區(qū)的坐標(biāo)
//所有使用clientX和clientY的都需要計(jì)算到滾動(dòng)條
//oDiv需要設(shè)置style為absolute
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
oDiv.style.top = oEvent.clientY + document.documentElement.scrollTop;
}
按鍵事件
基礎(chǔ)
onkeydown彪标、onkeyup仿便、onkeypress
document.onkeydown = function(ev) {
oEvent = ev || event;
oEvent.keyCode
}
小知識(shí)
oDiv.offsetLeft; //就是style中的left值 + margin-left值
ctrl+enter留言
oText.onKeydown = function(ev) {
var oEvent = ev || event;
//shiftKey,altKey
if(oEvent.ctrlKey && oEvent.keyCode == 13) {
}
}
默認(rèn)行為
屏蔽右鍵菜單
document.oncontextmenu = function(){
return false;
}
阻止表單提交
oForm.onsubmit = function() {
return false;
}
自定義右鍵菜單
<style>
#menu {
width: 50px;
background: #CCC;
border: 1px solid black;
position: absolute;
display: none;
}
</style>
<ul id="menu">
<li>登錄</li>
<li>回到首頁</li>
<li>注銷</li>
</ul>
//js
document.oncontextmenu = function(ev) {
var oEvent = ev || event;
var oUl = document.getElementById("menu");
oUl.style.display = "block;
//未加 scrollTop和scrollLeft
oUl.style.left = oEvent.clientX + 'px';
oUl.style.top = oEvent.clientY + 'px';
return false;
}
document.onclick = function () {
var oUl = document.getElementById("menu");
oUl.style.display = 'none';
}
拖拽事件
//onmousedown -> onmousemove -> onmouseup
window.onload = function() {
var oDiv = document.getElementById("div1");
var disX = 0;
var disY = 0;
oDiv.onmousedown = function(ev) {
var oEvent = ev || event;
disX = oEvent.clientX - oDiv.offsetLeft;
disY = oEvent.clientY - oDiv.offsetTop;
//防止拖出div范圍
document.onmousemove = function(ev) {
var oEvent = ev || event;
oDiv.style.left = oEvent.clientX - disX + 'px';
oDiv.style.top = oEvent.clientY - disY + 'px';
}
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
return false; //修正firefox下的bug谦去,空div拖拽bug
}