`
mutongwu
  • 浏览: 450097 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

简单拖拽的实现

阅读更多
来源:《Javascript权威指南第五版》
<body onload="init();">
<!-- Define the element to be dragged -->
<div style="position:absolute; left:100px; top:100px; width:250px;
            background-color: white; border: solid black;">
<!-- Define the "handle" to drag it with. Note the onmousedown 
 attribute. 
 -->
<div style="background-color: gray; border-bottom: dotted black;cursor:move;
            padding: 3px; font-family: sans-serif; font-weight: bold;"
     onmousedown="drag(this.parentNode, event);">
Drag Me  
</div>
<!-- Content of the draggable element -->
<p>This is a test. Testing, testing, testing.<p>This is a test.<p>Test.
</div>
<div id="zoomDiv"><img id="pic" src="/img/1.jpg" style="width:200px;height:200px;" /></div>
</body>


/**
 * Drag.js: drag absolutely positioned HTML elements.
 *
 * This module defines a single drag( ) function that is designed to be called
 * from an onmousedown event handler. Subsequent mousemove events will
 * move the specified element. A mouseup event will terminate the drag.
 * If the element is dragged off the screen, the window does not scroll.
 * This implementation works with both the DOM Level 2 event model and the
 * IE event model.
 *
 * Arguments:
 *
 *   elementToDrag: the element that received the mousedown event or
 *     some containing element. It must be absolutely positioned. Its
 *     style.left and style.top values will be changed based on the user's
 *     drag.
 *
 *   event: the Event object for the mousedown event.
 **/
function drag(elementToDrag, event) {
    // The mouse position (in window coordinates)
    // at which the drag begins
    var startX = event.clientX, startY = event.clientY;

    // The original position (in document coordinates) of the
    // element that is going to be dragged. Since elementToDrag is
    // absolutely positioned, we assume that its offsetParent is the
    // document body.
    var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;

    // Even though the coordinates are computed in different
    // coordinate systems, we can still compute the difference between them
    // and use it in the moveHandler( ) function. This works because
    // the scrollbar position never changes during the drag.
    var deltaX = startX - origX, deltaY = startY - origY;

    // Register the event handlers that will respond to the mousemove events
    // and the mouseup event that follow this mousedown event.
    if (document.addEventListener) {  // DOM Level 2 event model
        // Register capturing event handlers
        document.addEventListener("mousemove", moveHandler, true);
        document.addEventListener("mouseup", upHandler, true);
    }
    else if (document.attachEvent) {  // IE 5+ Event Model
        // In the IE event model, we capture events by calling
        // setCapture( ) on the element to capture them.
        elementToDrag.setCapture( );
        elementToDrag.attachEvent("onmousemove", moveHandler);
        elementToDrag.attachEvent("onmouseup", upHandler);
        // Treat loss of mouse capture as a mouseup event.
        elementToDrag.attachEvent("onlosecapture", upHandler);
    }
    else {  // IE 4 Event Model
        // In IE 4 we can't use attachEvent( ) or setCapture( ), so we set
        // event handlers directly on the document object and hope that the
        // mouse events we need will bubble up.
        var oldmovehandler = document.onmousemove; // used by upHandler( )
        var olduphandler = document.onmouseup;
        document.onmousemove = moveHandler;
        document.onmouseup = upHandler;
    }

    // We've handled this event. Don't let anybody else see it.
    if (event.stopPropagation) event.stopPropagation( );  // DOM Level 2
    else event.cancelBubble = true;                      // IE

    // Now prevent any default action.
    if (event.preventDefault) event.preventDefault( );   // DOM Level 2
    else event.returnValue = false;                     // IE

    /**
     * This is the handler that captures mousemove events when an element
     * is being dragged. It is responsible for moving the element.
     **/
    function moveHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        // Move the element to the current mouse position, adjusted as
        // necessary by the offset of the initial mouse-click.
        elementToDrag.style.left = (e.clientX - deltaX) + "px";
        elementToDrag.style.top = (e.clientY - deltaY) + "px";

        // And don't let anyone else see this event.
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }

    /**
     * This is the handler that captures the final mouseup event that
     * occurs at the end of a drag.
     **/
    function upHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        // Unregister the capturing event handlers.
        if (document.removeEventListener) {  // DOM event model
            document.removeEventListener("mouseup", upHandler, true);
            document.removeEventListener("mousemove", moveHandler, true);
        }
        else if (document.detachEvent) {  // IE 5+ Event Model
            elementToDrag.detachEvent("onlosecapture", upHandler);
            elementToDrag.detachEvent("onmouseup", upHandler);
            elementToDrag.detachEvent("onmousemove", moveHandler);
            elementToDrag.releaseCapture( );
        }
        else {  // IE 4 Event Model
            // Restore the original handlers, if any
            document.onmouseup = olduphandler;
            document.onmousemove = oldmovehandler;
        }

        // And don't let the event propagate any further.
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }
}

function init(){
    var pic = document.getElementById('pic');
    pic.onmousedown = function(e){
        if(!e)
            e = window.event;
        drag(this,e);
    }
}

分享到:
评论

相关推荐

    jquery简单实现拖拽效果

    本文将深入探讨如何使用jQuery实现简单的拖拽效果,让你的网页元素能够随心所欲地移动。 首先,拖拽效果的核心在于捕获鼠标事件,包括`mousedown`(鼠标按下)、`mousemove`(鼠标移动)和`mouseup`(鼠标释放)。...

    jquery实现简单图片的拖动

    "jquery实现简单图片的拖动"这个主题是关于如何利用jQuery的API来实现图片元素的拖放功能,这是一个常见的交互设计,使得用户可以通过鼠标拖动图片在页面上自由移动。 在jQuery中,实现图片拖动主要涉及到`...

    c# 实现任意控件的拖拽

    下面将详细介绍如何在C#中实现任意控件的拖拽功能。 首先,我们需要为控件添加鼠标事件处理程序。在C#中,这些事件包括`MouseDown`、`MouseMove`和`MouseUp`。`MouseDown`事件在鼠标按钮被按下时触发,`MouseMove`...

    C# 类似Visio图形拖拽实现

    通过以上步骤,你就可以在C#中实现一个简单的类似Visio的图形拖拽功能。随着需求的增加,可以扩展更多的图形类型和交互逻辑,如节点的旋转、缩放、连接线的样式选择等。这个WindowsFormsDemo项目将是一个很好的起点...

    使用 svg 实现拖拽效果

    以下是一个简单的SVG拖拽效果的JavaScript实现: ```html const draggableRect = document.querySelector('#draggable'); let isDragging = false; let initialMouseX, initialMouseY; draggableRect...

    Cms拖拽实现拖拽生成页面

    【标题】:“Cms拖拽实现拖拽生成页面”这一技术是现代内容管理系统(CMS)中常见的一种交互设计,它允许用户通过简单的拖放操作来自由构建和编辑网站页面。这种功能大大降低了非技术人员创建和管理网站内容的门槛,...

    JTable实现行间拖拽的最简单方法

    本文将详细介绍如何通过一种简单的方法,为`JTable`添加行间拖拽功能,而无需对已有代码进行大规模修改或实现复杂的DnD接口。 首先,理解`JTable`的基本结构是至关重要的。`JTable`由`TableModel`、`...

    Web 前端拖拽实现实例分析

    本文将深入探讨如何在Web前端实现拖放功能,通过实例分析不同实现方式的优缺点,帮助开发者选择最适合项目需求的解决方案。 首先,让我们了解拖放的基本原理。拖放功能涉及两个主要事件:`dragstart`、`drag`、`...

    MFC画圆拖动,简单实现

    在本项目中,"MFC画圆拖动,简单实现"是一个基于中国地质大学C++课程的编程课题,主要目标是使用Microsoft Foundation Classes (MFC) 框架来创建一个用户界面,允许用户在界面上绘制并拖动圆形。MFC是微软提供的一套...

    C#实现树型结构TreeView节点拖拽的简单功能,附全部源码,供有需要的参考

    C#实现树型结构TreeView节点拖拽的简单功能 在软件开发中,一个树形结构的数据若不支持拖拽功能,那么使用起来就会很糟糕,用户体验也不会太好。因此,在组织机构管理模块中实现树型结构TreeView节点拖拽的简单功能...

    javaScript实现DIV简单拖拽

    javaScript实现DIV简单拖拽

    table实现列宽的拖动效果

    "table实现列宽的拖动效果"是一个常见的需求,特别是在数据展示或者数据分析的应用中,用户可能需要自定义表格列的宽度以更好地查看和理解数据。这篇博客文章 "https://jifeng3321.iteye.com/blog/2403674" 提到的...

    可以实现拖拽的案例

    在这个“可以实现拖拽的案例”中,可能包含了一个简单的拖拽实现,如一个文件管理器或者画板应用,用户可以通过拖拽文件或图形元素来完成操作。通过分析源代码,我们可以学习如何在实际项目中应用这些技术,提升应用...

    C#实现简单的拖拽功能

    在这个“C#实现简单的拖拽功能”的项目中,开发者使用了Visual Studio 2017来创建了一个能处理图片拖放的示例应用。以下是关于C#中实现拖放功能的关键知识点: 1. **Windows Forms**:这个项目基于Windows Forms...

    jquery实现拖拽

    总结,jQuery的拖拽功能通过`.draggable()`和`.droppable()`方法实现了元素的拖动和放置,配合适当的参数和回调函数,可以创建出各种用户友好的交互体验。在实际项目中,可以结合具体的业务需求,对这些方法进行扩展...

    js简单实现拖动

    本文将详细讲解如何使用纯JavaScript来实现一个简单的拖动功能,并通过实例代码进行解析。 首先,我们需要理解拖动的基本原理。拖动操作涉及到鼠标事件(如`mousedown`、`mousemove`和`mouseup`)以及元素的位置...

    学习使用ReactDnD实现嵌套列表的拖拽排序

    在这个主题中,我们将深入探讨如何利用ReactDnD来实现嵌套列表的拖拽排序。 首先,我们需要安装ReactDnD库。通过npm或yarn可以轻松完成: ```bash npm install react-dnd react-dnd-html5-backend # 或者 yarn add...

    简易拖动面板的实现

    简易拖动面板的制作,分为拖动的目标,拖动的元素,拖动范围

    基于jquery+canvas实现的拖动插件

    实现拖动功能的关键在于监听鼠标的事件,包括`mousedown`(鼠标按下)、`mousemove`(鼠标移动)和`mouseup`(鼠标释放)。当`mousedown`事件触发时,记录下鼠标点击时的位置,并设置一个标志表示拖动已经开始。在`...

    纯js实现可拖拽和点击的悬浮球

    我们将监听用户的鼠标事件,包括`mousedown`(鼠标按下)、`mousemove`(鼠标移动)和`mouseup`(鼠标释放),以实现拖拽功能。首先,我们需要获取到悬浮球元素,并设置初始位置: ```javascript var draggableBall...

Global site tag (gtag.js) - Google Analytics