js实现拖拽事件的方法实例
来源:动视网
责编:小采
时间:2020-11-27 19:58:50
js实现拖拽事件的方法实例
js实现拖拽事件的方法实例:本文主要和大家分享js实现拖拽事件的方法实例,希望能帮助到大家。HTML<body> <p></p></body>CSSp{ position: absolute; width: 200px; height: 200px; background: #369 }JSwindow.on
导读js实现拖拽事件的方法实例:本文主要和大家分享js实现拖拽事件的方法实例,希望能帮助到大家。HTML<body> <p></p></body>CSSp{ position: absolute; width: 200px; height: 200px; background: #369 }JSwindow.on

本文主要和大家分享js实现拖拽事件的方法实例,希望能帮助到大家。
HTML
CSS
p{ position: absolute; width: 200px; height: 200px; background: #369
}JS
window.onload = function(){
var op = document.getElementsByTagName("p")[0];
/*鼠标点击的位置距离p左边的距离 */
var disX = 0;
/*鼠标点击的位置距离p顶部的距离*/
var disY = 0;
op.onmousedown = function(){
var e = e || window.event;
disX = e.clientX - op.offsetLeft;
disY = e.clientY- op.offsetTop;
document.onmousemove = function(e){
var e = e || window.event;
// 横轴坐标
var leftX = e.clientX - disX;
// 纵轴坐标
var topY =e.clientY - disY;
if( leftX < 0 ){
leftX = 0;
} /* 获取浏览器视口大小 document.document.documentElement.clientWidth*/
else if( leftX > document.documentElement.clientWidth - op.offsetWidth ){
leftX = document.document.documentElement.clientWidth - op.offsetWidth;
}
if( topY < 0 ){
topY = 0;
}
else if( topY > document.documentElement.clientHeight -op.offsetHeight ){
topY = document.documentElement.clientHeight - op.offsetHeight;
}
op.style.left = leftX + "px";
op.style.top = topY+"px";
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}
}
js实现拖拽事件的方法实例
js实现拖拽事件的方法实例:本文主要和大家分享js实现拖拽事件的方法实例,希望能帮助到大家。HTML<body> <p></p></body>CSSp{ position: absolute; width: 200px; height: 200px; background: #369 }JSwindow.on