JS实现面板拖动及兼容性处理方法

本文介绍如何使用JavaScript实现面板的拖动功能,并针对IE10以下浏览器的兼容性问题提供解决方案,包括封装获取类名对象的方法以及防止面板移出屏幕的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//IE10以下浏览器不支持该方法故需要封装新的获取类名对象方法

//var parent=document.getElementsByClassName("son");

function getByClass(classname,parent){
var oParent=parent?document.getElementById(parent):document;
var eles=[];
var elements=oParent.getElementsByTagName("*");
for(var i=0;i<elements.length;i++){
if(elements[i].className==classname){
eles.push(elements[i]);
}
}
return eles;
}
window.onload=newfunction;

function newfunction(){
//获取<div class="son"></div>这个对象,CSS样式就不多写了,注意position一定要为absolute
Target=getByClass("son","")[0];
//当鼠标按下对象时,调用fnDown函数
Target.onmousedown=fnDown;
}
function fnDown(event){
//获取鼠标箭头位置方法
event=event||window.event;
//光标按下时光标和面板之间的距离
disX=event.clientX-Target.offsetLeft;
disY=event.clientY-Target.offsetTop;
//鼠标移动
document.onmousemove=function(event){
event=event||window.event;
fnMove(event,disX,disY);
}
//释放鼠标时注销移动事件
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
function fnMove(e,posX,posY){
l=e.clientX-posX;

t=e.clientY-posY;

       //防止面板移出屏幕处理方法

windowW=document.documentElement.clientWidth||document.body.clientWidth;
windowH=document.documentElement.clientHeight||document.body.clientHeight;
maxW=windowW-Target.offsetWidth;
maxH=windowH-Target.offsetHeight;
if(l<0){
l=0;
}else if(l>maxW){
l=maxW;
}
if(t<0){
t=0;
}else if(t>maxH){
t=maxH;
}
Target.style.left=l+"px";
Target.style.top=t+"px";

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值