Giter Site home page Giter Site logo

js-demo-drag's Introduction

用原生 JS 实现自由拖拽一个 div

实现思路

  1. 用 onmousedown onmousemove onmouseup 获取鼠标位置
  2. 将 div 弄成绝对定位,将鼠标的位置赋值到 div 的 top 和 left 上
  3. 用一个 boolean 值来做开关

下载运行

  • clone 或者下载压缩包之后
  • 使用 http-server -c-1 命令行运行

该项目相关知识点

onmousedown onmousemove onmouseup 三个事件

  • onmousedown:在当前元素上鼠标按下瞬间会触发mousedown事件;
  • onmousemove:当用户在当前元素上移动鼠标时会触发mousemove事件;
  • onmouseup:当用户在当前元素上放开鼠标某个按键时会触发mouseup事件;

如何将 body 变成和页面可视部分一样大

body {
    box-sizing: border-box;
    height: 100vh;
    margin: 0;
}

js 为一个元素添加类名的两种方式

  • 操作 classList 数组,如 div.classList = ["demo"]
  • 赋值 className ,div.className = "demo"

body 元素是有默认 margin 的。

JS 的 .style 只能拿到内联样式

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.