>  기사  >  웹 프론트엔드  >  JS_javascript 기술로 구현된 사용자 정의 웹 페이지 드래그 클래스

JS_javascript 기술로 구현된 사용자 정의 웹 페이지 드래그 클래스

WBOY
WBOY원래의
2016-05-16 15:33:34961검색

이 기사의 예에서는 JS에서 구현된 사용자 정의 웹 페이지 드래그 클래스를 설명합니다. 참고하실 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

먼저 실행 중인 효과의 스크린샷을 살펴보세요.

온라인 데모 주소는 다음과 같습니다.

http://demo.jb51.net/js/2015/js-zdy-web-drug-pic-style-codes/

구체적인 코드는 다음과 같습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/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&#63;this.attachEvent('on'+e,f):this.addEventListener(e,f,b);
}
d.removeListener=function(e,f,b){
 this.detachEvent&#63;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&#63;this.attachEvent('on'+e,f):this.addEventListener(e,f,b);
 }
 o.removeListener=function(e,f,b){
  this.detachEvent&#63;this.detachEvent('on'+e,f):this.removeEventListener(e,f,b);
 }
 o.startDrag=function(obj){//参数obj默认为o本身,可以传其它参数以确定要移动的对象
  var obj=obj&#63;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",stopDrag,false);
   }
  },false);
  var stopDrag=function(){
   d.removeListener("mousemove",move,false);
   d.removeListener("mouseup",stopDrag,false);
  }
  var move=function(e){
   e||event;
   window.getSelection &#63; window.getSelection().removeAllRanges() :
    document.selection.empty();
   if(e.preventDefault)e.preventDefault();//这两句便是解决firefox拖动问题的.
   with (obj.style){
    position="absolute"
    left=e.clientX-sx+"px";
    top=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 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.