分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

JS-JQ-拖拽

发布时间:2023-09-06 01:27责任编辑:彭小芳关键词:暂无标签

拖拽的原理很简单

    1、第一步:需要基本的概念,需要这些事件:

    onmousedown()鼠标按下、

    onmousemove()鼠标移动、

    onmouseup()鼠标抬起、

   2、第二步:你需要了解事件的状态,也就是获取鼠标的位置:

  window.Event :代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。

  oEvent.clientX:获取鼠标的横坐标

!!!-  CSS

<style>
  .div1{width:200px;height:200px;background:rosybrown;position:absolute;}
</style>

!!! - HTML

<div class="div1"></div>

!!! - JavaScript

window.onload=function()
{
  var div1=document.getElementsByClassName(‘div1‘)[0];
  var l=0;
  var t=0;
  div1.onmousedown=function(ev)
  {
    var oEvent=ev||event;
    var disX=oEvent.clientX-div1.offsetLeft;     
    var disY=oEvent.clientY-div1.offsetTop;

    document.onmousemove=function(ev)
    {
      var oEvent=ev||event;
      l=oEvent.clientX-disX;
      t=oEvent.clientY-disY;
      div1.style.left=l+"px";
      div1.style.top=t+"px";
    }
    document.onmouseup=function()
    {
      document.onmouseup=null;
      document.onmousemove=null;
    }
  }

}

!!! -  JQuery

$(function(){
  var l=0;
  var t=0;
  $(‘.div1‘).mousedown(function(ev){
    var oEvent=ev||event;
    var disX=oEvent.clientX-$(this).offset().left;
    var disY=oEvent.clientY-$(this).offset().top;
    $(document).mousemove(function(ev){
      var oEvent=ev||event;
      l=oEvent.clientX-disX;
      t=oEvent.clientY-disY;
      $(‘.div1‘).css(‘left‘,l);
      $(‘.div1‘).css(‘top‘,t);
      console.log(‘移动‘);
    })
    $(document).mouseup(function(){
      $(document).off();
    })
  })
})*/

JS-JQ-拖拽

原文地址:http://www.cnblogs.com/xiaoyangtian/p/7922065.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved