浏览器兼容设置
都以点击事件 onclick
为例:
事件对象获取
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 为获取到的事件
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