JS实现的自定义网页拖动类
网络编程 2021-07-04 21:03www.168986.cn编程入门
这篇文章主要介绍了JS实现的自定义网页拖动类,涉及页面元素响应鼠标事件动态改变属性的相关实现技巧,需要的朋友可以参考下
本文实例讲述了JS实现的自定义网页拖动类。分享给大家供大家参考,具体如下:
先来看运行效果截图如下:
在线演示地址如下:
具体代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://.w3./TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://.w3./1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>自写的拖动类……</title> <script type="text/javascript"> var d=document;//给document对象一个通用的事件侦听方法 d.addListener=function(e,f,b){ this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b); } d.removeListener=function(e,f,b){ this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b); } function $(){//接收一个id参数,返回带有startDrag方法的对象 var o=document.getElementById(arguments[0]); o.addListener=function(e,f,b){ this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b); } o.removeListener=function(e,f,b){ this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b); } o.startDrag=function(obj){//参数obj默认为o本身,可以传其它参数以确定要移动的对象 var obj=obj?obj:o; var sx,sy; o.style.cursor="move"; o.addListener("mousedown",function(e){ e||event; if(e.button==1||e.button==0){ sx=e.clientX-obj.offsetLeft;sy=e.clientY-obj.offsetTop; d.addListener("mousemove",move,false); d.addListener("mouseup",sDrag,false); } },false); var sDrag=function(){ d.removeListener("mousemove",move,false); d.removeListener("mouseup",sDrag,false); } var move=function(e){ e||event; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); if(e.preventDefault)e.preventDefault();//这两句便是解决firefox拖动问题的. with (obj.style){ position="absolute" left=e.clientX-sx+"px"; =e.clientY-sy+"px"; } } } return o; } window.onload=function(){$("ok").startDrag($("os"))}//本例中拖动ok元素,移动其父元素 </script> <style type="text/css"> *{margin:0;padding:0} #ok{width:215px;height:170px;background:url(images/sample1.gif)} #os{width:400px;height:300px;background:#09f;left:300px} #os2{width:400px;height:300px;background:#f90;} </style> </head> <body> <div id="os"><p id="ok"></p></div> <div id="os2"></div> </body> </html>
希望本文所述对大家JavaScript程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程