瀏覽器兼容設置
都以點擊事件 onclick
爲例:javascript
事件對象獲取
document.onclick = function(ev) { let e = ev || window.event; }
獲取鍵碼
let w = e.which || e.keyCode;
目標對象 / 觸發對象
button.onclick = function() { let target = e.target || window.event.srcElement; }
阻止超連接默認行爲的函數
e 爲獲取到的事件java
function preDef(e) { if(e.preventDefault) { e.preventDefault(); } else { window.event.returnValue = false; } }
事件監聽器
function addEvent(node,evenType,funName) { if(node.addEventListener) { node.addEventListener(evenType, funName,false); } else { node.attachEvent('on' + evenType, funName); } }
function removeEvent(node,evenType,funName) { if(node.removeEventListener) { node.removeEventListener(evenType, funName,false); } else { node.detachEvent('on' + evenType, funName); } }
獲取當前窗口的寬高
let Width = document.documentElement.clientWidth || document.body.clientWidth; let Height = document.documentElement.clientHeight || document.body.clientHeight;
拖拽封裝
普通拖拽封裝
function drag(node) { node.onmousedown = function(ev) { let e = ev || window.event; // 獲取鼠標到 node 左上角的相對位置 let offSetX = e.clientX - node.offsetLeft; let offSetY = e.clientY - node.offsetTop; // 鼠標移動時,計算 node 左上角應該在的位置 document.onmousemove = function(ev) { let e = ev || window.event; node.style.left = e.clientX - offSetX + 'px'; node.style.top = e.clientY - offSetY + 'px'; } } document.onmouseup = function() { document.onmousemove = null; } }
限制出界的拖拽封裝
function limitDrag(node) { node.onmousedown = function (ev) { let e = ev || window.event; // 獲取鼠標到 node 左上角的相對位置 let offSetX = e.clientX - node.offsetLeft; let offSetY = e.clientY - node.offsetTop; document.onmousemove = function (ev) { let e = ev || window.event; // 鼠標移動時,計算 node 左上角應該在的位置 let x = e.clientX - offSetX; let y = e.clientY - offSetY; // 限制出界 // 獲取當前窗口的寬高 let Width = document.documentElement.clientWidth || document.body.clientWidth; let Height = document.documentElement.clientHeight || document.body.clientHeight; if (x <= 0) { x = 0; } if (x >= Width - node.offsetWidth) { x = Width - node.offsetWidth } if (y <= 0) { y = 0; } if (y >= Height - node.offsetHeight) { y = Height - node.offsetHeight } node.style.left = x + 'px'; node.style.top = y + 'px'; } } document.onmouseup = function () { document.onmousemove = null; } }
針對拖拽封裝的小栗子:
https://blog.csdn.net/Web_blingbling/article/details/107868162
node