JS事件处理

鼠标事件

document.onclick = function(ev) {
  var oEvent = ev || event; //ie下ev不存在,firefox默认传一个ev
  oEvent.clientX; //鼠标点击时的位置
}

事件冒泡

//取消事件冒泡
oBtn.onclick = function(ev) {
  var oEvent = ev || event;
  oEvent.cancelBubble = true;
}

控件随着鼠标移动

document.onmousemove = function(ev) {
  var oEvent = ev || event;
  //clientX和clientY代表的是可视区的坐标
  //所有使用clientX和clientY的都需要计算到滚动条
  //oDiv需要设置style为absolute
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  oDiv.style.top = oEvent.clientY + document.documentElement.scrollTop;
}

按键事件

基础

onkeydown、onkeyup、onkeypress

document.onkeydown = function(ev) {
  oEvent = ev || event;
  oEvent.keyCode
}

小知识

oDiv.offsetLeft; //就是style中的left值 + margin-left值

ctrl+enter留言

oText.onKeydown = function(ev) {
  var oEvent = ev || event;
  //shiftKey,altKey
  if(oEvent.ctrlKey && oEvent.keyCode == 13) {

  }
}

默认行为

屏蔽右键菜单

document.oncontextmenu = function(){
  return false;
}

阻止表单提交

oForm.onsubmit = function() {
  return false;
}

自定义右键菜单




//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
  }

你可能感兴趣的:(JS事件处理)