木灵鱼儿
阅读:1228
原生js实现拖动效果
以前写过但是太复杂了,这次直接用原生js写了,相对来说简单了很多。
html,
body {
margin: 0;
padding: 0;
}
#box {
position: absolute;
width: 200px;
height: 200px;
border: 2px solid #92cccc;
background: rgba(0, 0, 0, 0.5);
}
<div id='box'></div>
var box = document.getElementById("box");
var spaceX = null;
spaceY = null;
winWidth = null;
winHeight = null;
//按下的时候计算好间距
box.addEventListener("mousedown", function (event) {
const e = event || window.event;
e.stopPropagation();
//计算环境得到数据
//间距
spaceX = e.clientX - box.offsetLeft;
spaceY = e.clientY - box.offsetTop;
//可视宽高
winWidth = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
winHeight = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
//添加事件
document.addEventListener('mousemove', boxMousemove, false);
}, false);
//删除移动事件
box.addEventListener("mouseup", function () {
document.removeEventListener('mousemove', boxMousemove, false);
this.style.cursor = "default";
});
//移动事件
function boxMousemove(event) {
const e = event || window.event;
const realX = e.clientX - spaceX;
const realY = e.clientY - spaceY;
//x轴移动
if (realX + box.offsetWidth >= winWidth) {
box.style.left = winWidth - box.offsetWidth + "px";
} else if (realX < 0) {
box.style.left = 0 + "px";
} else {
box.style.left = e.clientX - spaceX + "px";
};
//y轴移动
if (realY + box.offsetHeight >= winHeight) {
box.style.top = winHeight - box.offsetHeight + "px";
} else if (realY < 0) {
box.style.top = 0 + "px";
} else {
box.style.top = e.clientY - spaceY + "px";
};
//鼠标样式
box.style.cursor = "move";
}
效果图
版权申明
本文系作者 @木灵鱼儿 原创发布在木灵鱼儿 - 有梦就能远航站点。未经许可,禁止转载。
相关推荐
使用vue.draggable拖拽组件遇到的一些问题
资源github:vue.draggable中文文档:vue.draggable中文文档api参考文档:sortablejsvue.draggable是基于sortablejs的vue封装,所有有些api官方并不会有过多的解释,可以去sortablejs查看下拖拽无法触发页面滚动当拖拽的内容大于页面宽高时,页面滚动就是一个必然的需求,但是vue.draggable默认情况并不能触发滚动。官方设置里有一个属性:scroll,如果为true时就能触发滚动,但是默认属性就是true;所以这个配置可以说是无效的。解决方案:cannot set scrollSensitivity19年的时候就有提...

element table表格使用sortablejs插件进行拖拽
在表格里面进行拖拽,肯定没法用组件的形式,因为会破坏table的结构,所以只能从 dom上入手。安装插件yarn add sortablejs --dev中文说明站点:sortablejs中文网使用<template> <el-table :data="tbody" id="appTable" row-key="id"> ... </el-table> </template> <script> import Sortable from "so...
完美仿微信图片拖动效果
之前一直没时间搞,今天得空研究了下,完美啊,搞定了我以前的一个心病。预览图介绍没有js基础的就不要看了,这是很骨架的源码,但是核心部分都可以用,目前只做了电脑端,移动端事件不一样,只需要改几个参数就可以了,丢博客也是给自己做个备份。有兴趣的也可以看看源码[hide]html<div id='box'></div>csshtml, body { margin: 0; padding: 0; background-color: antiquewhite; } #box { position: a...
