原生js--鼠标事件
鼠标事件对象几个重要的属性:
clientX 窗口坐标,加上垂直滚动可以得到文档纵坐标
clientY 窗口坐标,加上水平滚动可以得到文档横坐标
altKey boolean值,点击时是否按下了alt键
ctrlKey boolean值,点击时是否按下了ctrl键
metaKey boolean值,点击时是否按下了meta键
shiftKey boolean值,点击时是否按下了shift键
button 点击时按下的是鼠标的哪个键(不同浏览器的赋值不同,不易使用)
收录拖动文档元素的js
/**
* 拖动绝对定位的HTML元素
*
该方法依赖之前收集的getScrollOffset方法
*/
function drag( elementToDrag, event
){
// 初始化鼠标位置,转换为文档坐标
var scroll =
getScrollOffset(),
startX =
event.clientX + scroll.x,
startY =
event.clientY + scroll,y,
//
这里假设了elementToDrag的offsetParent是文档的body元素,似乎会有问题
origX = elementToDrag.offsetLeft,
origY = elementToDrag.offsetTop,
deltaX = startX - origX,
deltaY = startY - origY;
if(
document.addEventListener ){
document.addEventListener( "mousemove", movehandler, true
);
document.addEventListener(
"mouseup", upHandler, true );
}else if(
document.attachEvent ){
//
IE的事件模型中,捕获事件是通过调用元素上的setCapture()实现的
elementToDrag.setCapture();
elementToDrag.attachEvent( "onmousemove", moveHandler );
elementToDrag.attachEvent( "onmouseup", upHandler
);
//
作为mouseup事件看待鼠标捕获的丢失???
elementToDrag.attachEvent( "onlosecapture", upHandler );
}
if( event.stopPropagation )
event.stopPropagation();
else event.cancelBubble =
true;
// 现在阻止任何默认操作
if(
event.preventDefault ) event.preventDefault();
else
event.returnValue = false;
function moveHandler( e
){
if( !e ) e =
window.event;
var scroll =
getScrollOffset();
elementToDrag.style.left = ( e.clientX + scroll.x - deltaX ) +
"px";
elementToDrag.style.top = (
e.clientY + scroll.y -deltaY ) + "px";
if( e.stopPropagation ) e.stopPropagation();
else e.cancelBubble = true;
}
function upHandler( e ){
if( !e ) e = window.event;
if( document.removeEventListener ){
document.removeEventListener(
"mouseup", upHandler, true );
document.removeEventListener( "mousemove", movehandler,
true );
}else if( document.attachEvent
){
elementToDrag.detachEvent( "onlosecapture", upHandler );
elementToDrag.detachEvent(
"onmouseup", upHandler );
elementToDrag.detachEvent( "onmousemove", movehandler );
elementToDrag.releasecapture();
}
if( e.stopPropagation )
e.stopPropagation();
else
e.cancelBubble = true;
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。