Giter Site home page Giter Site logo

js_move_drag's Introduction

js_move_drag

js实现的简单的鼠标拖拽效果 首先我实现的效果是:

鼠标按下后,才可以执行后续效果
鼠标已经按下,然后鼠标移动,需要拖拽的元素跟着一起移动
鼠标松开,然后停止移动

大步骤就是这样一个过程,其实对应的就是三个事件:

onmousedown
onmousemove
onmouseup

然后我们来看这三个事件发生时分别作做什么事。

当鼠标按下时,我们得记录当前元素的位置newSite。同时设置一个标记,用于表示此时鼠标时按下的状态,方便鼠标移动事件的执行。 当鼠标松开时,我们要将标记改变,说明此时鼠标松开了,当鼠标移动时就不能再移动元素了。 当鼠标按下并且移动时,我们就要记录鼠标每次移动的位置currentSite,currentSite和newSite的差值就是鼠标移动的距离, 同时也是元素应该移动的距离,然后设置元素的位置就OK了。

当然有个很重要的点就是需要移动的元素的position属性应该设为absolute或者relative,这样元素才可以移动。 同时,如果该元素内部有可能导致浏览器默认事件发生的元素时,要阻止默认事件的发生,例如里面有一个图片时, 点击拖动的时候浏览器会默认弹出一个新窗口显示该图片,这时我们应该阻止这个事件的发生。

js_move_drag's People

Contributors

victor151222 avatar

Stargazers

chen lu avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.