×

jquery实现拖动效果

作者:Terry2017.01.25来源:Web前端之家浏览:8011评论:0
关键词:JQueryJS

因为想实现相框的拖到,找了半天的原因愣是没有找到错误,所以,只能翻看源码了 

如何实现拖动效果?

 

首先分析下拖动效果原理:
1.当鼠标在被拖动对象上按下鼠标(触发onmousedown事件,且鼠标在对象上方)
2.开始移动鼠标(触发onmousemove事件)
3.移动时更显对象的top和left值
4.鼠标放开停止拖动(触发onmouseup事件)
注意:拖动的对象必须是定位对象(即设置了position:absolute或 relative)。 

也就是说拖动事件=onmousedown事件+onmousemove事件 

整个过程就是处理这三个事件来模拟drag事件
现在看看我实现的源代码: 

html代码: 

<div class="drag">
 <p class="title">标题(点击标题拖动)</p>
</div>

<div class="drag1">
 <p class="title">标题</p>
 点击我移动
</div>

 

jquery插件代码:

(function($){
 $.fn.drag=function(options){

 //默认配置
 var defaults = {
 handler:false,
 opacity:0.5
 };

 // 覆盖默认配置
 var opts = $.extend(defaults, options);

 this.each(function(){

 //初始标记变量
 var isMove=false,
 //handler如果没有设置任何值,则默认为移动对象本身,否则为所设置的handler值
 handler=opts.handler?$(this).find(opts.handler):$(this),
 _this=$(this), //移动的对象
 dx,dy;

 $(document)
 //移动鼠标,改变对象位置
 .mousemove(function(event){
 // console.log(isMove);
 if(isMove){

 //获得鼠标移动后位置
 var eX=event.pageX,eY=event.pageY;

 //更新对象坐标
 _this.css({'left':eX-dx,'top':eY-dy});

  }
 })

 //当放开鼠标,停止拖动
 .mouseup(function(){
 isMove=false;
 _this.fadeTo('fast', 1);
 //console.log(isMove);
  });

 handler
 //当按下鼠标,设置标记变量isMouseDown为true
 .mousedown(function(event){

 //判断最后触发事件的对象是否是handler
 if($(event.target).is(handler)){

 isMove=true;
 $(this).css('cursor','move');

 //console.log(isMove);
 _this.fadeTo('fast', opts.opacity);

 //鼠标相对于移动对象的坐标
 dx=event.pageX-parseInt(_this.css("left"));
 dy=event.pageY-parseInt(_this.css("top"));

  }
   });
  });
 };
 })(jQuery);

 

调用方法:

$(function(){

 //拖动标题
 $(".drag").drag({
handler:$('.title'),//操作拖动的对象,此对象必须是移动对象的子元素
opacity:0.7 //设置拖动时透明度
});

 //拖动主体对象
 $(".drag1").drag({
 opacity:0.7
 });

 });

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/svg1485273600610.html

网友评论文明上网理性发言 已有0人参与

发表评论: