关键词:
一、写在前面
写这个原因很简单,有这么一个需求如下:
编写代码实现以下要求:画一个矩形,拖拽矩形的4个角可以将矩形缩放,在矩形上按住鼠标拖动可以移动该矩形的位置。
要求如下:
- 整个矩形的最小大小为 5px * 5px,缩放到最小时不能发生移动;
- 鼠标快速移动时移动和缩放效果要保持流畅。
二、直接上代码
还是按照步骤一步一步的来吧。首先是要创建一个矩形,然后再写逻辑,下面一个矩形就画好了。。。
但是似乎屏幕上啥也没有。。 是的没宽高,所以就看不到了。别着急,继续画。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现拖拽缩放元素(工厂模式)</title>
<style type="text/css">
*
padding: 0;
margin: 0;
#app-warpper
position: absolute;
cursor: move;
</style>
</head>
<body>
<div id="app-warpper"></div>
</body>
<script>
//todo
</script>
</html>
这里开始写逻辑了,我们选择用工厂模式来创建一个可以拖拽编辑的矩形。下面就是代码工厂部分.若想看逻辑的可以一步一步的看代码注释,大概的思路就是,你需要计算你当前按下鼠标的位置,然后在移动的时候获取的鼠标位置与刚刚鼠标按下的位置进行一个计算.有个差值,这个差值就是需要移动的距离.
矩形缩放的时候就稍微要复杂一点了,大概思路如下:
- 左上角缩放: 计算 left坐标,top的坐标,以及宽高;
- 右上角缩放: 计算top坐标 和 宽高即可.
- 右下角缩放: 计算宽高即可.
- 左下角缩放: 计算left,top 和宽高.
可能描述有点抽象,但是动手写一遍的时候就知道大概是咋回事了.
/**
* 创建一个可拖拽的矩形
*/
function CreateDragRect(elm, options = )
if (!elm) throw new Error('el 必须是一个document对象');
this.rect = elm;
this.isLeftMove = true;
this.isTopMove = true;
this.rectDefaultPosition = options.position || 'fixed';
this.rectDefaultLeft = options.x || 0;
this.rectDefaultTop = options.y || 0;
this.rectWidth = options.width || 100;
this.rectHeight = options.height || 100;
this.rectMinWidth = options.rectMinWidth || 5; //最小宽度(超过之后不允许再缩放)
this.rectMinHeight = options.rectMinHeight || 5; //最小高度(超过之后不允许再缩放)
this.rectBackgroundColor = options.background || '#ccc';
this.dragIconSize = options.dragIconSize || '4px';
this.dragIconColor = options.dragIconColor || '#f00';
//主矩形是否可以移动
this.isMove = false;
this.initStyle();
this.bindDragEvent(this.rect);
/**
* 主矩形绑定move事件
*/
CreateDragRect.prototype.bindDragEvent = function (dom, position)
const _this = this;
dom.onmousedown = function (event)
event.stopPropagation();
//按下矩形的时候可以移动,否则不可移动
_this.isMove = !position;
// 获取鼠标在wrapper中的位置
let boxX = event.clientX - dom.offsetLeft;
let boxY = event.clientY - dom.offsetTop;
//鼠标移动事件(如果计算太高,有拖影)
document.onmousemove = _this.throttle(function (moveEv)
let ev = moveEv || window.event;
ev.stopPropagation();
let moveX = ev.clientX - boxX;
let moveY = ev.clientY - boxY;
switch (position)
case 'top-left': //左上: 需计算top left width
_this.nwRectSize(moveX, moveY);
break;
case 'top-right': //右上 计算top 和 height
_this.neRectSize(moveX, moveY);
break;
case 'right-bottom': //只需计算当前鼠标位置
_this.seRectSize(moveX, moveY);
break;
case 'left-bottom': //计算left偏移量,计算w
_this.swRectSize(moveX, moveY);
break;
default: //拖拽矩形
if (!_this.isMove) return null;
_this.moveRect(ev.clientX - boxX, ev.clientY - boxY);
, 15);
//鼠标松开,移除事件
document.onmouseup = function (event)
document.onmousemove = null;
document.onmouseup = null;
// 存储当前的rect的宽高
_this.rectWidth = _this.rect.offsetWidth;
_this.rectHeight = _this.rect.offsetHeight;
// 获得当前矩形的offsetLeft 和 offsetTop
_this.rectOffsetLeft = _this.rect.offsetLeft;
_this.rectOffsetTop = _this.rect.offsetTop;
/**
* 初始化样式
*/
CreateDragRect.prototype.initStyle = function ()
this.rect.style.position = this.rectDefaultPosition;
this.rect.style.width = this.rectWidth + 'px';
this.rect.style.height = this.rectHeight + 'px';
this.rect.style.left = this.rectDefaultLeft + 'px';
this.rect.style.top = this.rectDefaultTop + 'px';
this.rect.style.background = this.rectBackgroundColor;
//依次为上 右 下 左
let dragIcons = [
cursor: 'nw-resize',
x: 'top',
y: 'left'
,
cursor: 'ne-resize',
x: 'top',
y: 'right'
,
cursor: 'se-resize',
x: 'right',
y: 'bottom'
,
cursor: 'sw-resize',
x: 'left',
y: 'bottom'
];
for (let i = 0, l = dragIcons.length; i < l; i++)
let icon = document.createElement('i');
icon.id = Math.random().toString(36).substring(7);
icon.style.display = 'inline-block';
icon.style.width = this.dragIconSize;
icon.style.height = this.dragIconSize;
icon.style.position = 'absolute';
icon.style.zIndex = 10;
icon.style.cursor = dragIcons[i].cursor;
icon.style.backgroundColor = this.dragIconColor;
icon.style[dragIcons[i].x] = -parseInt(icon.style.width) / 2 + 'px';
icon.style[dragIcons[i].y] = -parseInt(icon.style.height) / 2 + 'px';
//绑定四个角的拖拽事件
this.bindDragEvent(icon, `$dragIcons[i].x-$dragIcons[i].y`);
//插入到矩形
this.rect.appendChild(icon);
;
/**
* 移动主矩形
*/
CreateDragRect.prototype.moveRect = function (x, y)
if (this.isTopMove && this.isLeftMove)
this.rect.style.left = x + 'px';
this.rect.style.top = y + 'px';
;
/**
* 移动主矩形缩放 - 左上
*/
CreateDragRect.prototype.nwRectSize = function (x, y)
//计算是否是最小宽度
const width, height, isLeftMove, isTopMove = this.getMinSize(this.rectWidth - x, this.rectHeight - y);
if (isTopMove)
this.rect.style.top = this.rectOffsetTop + y + 'px';
this.rect.style.height = height + 'px';
if (isLeftMove)
this.rect.style.left = this.rectOffsetLeft + x + 'px';
this.rect.style.width = width + 'px';
;
/**
* 移动主矩形缩放 - 左下
*/
CreateDragRect.prototype.swRectSize = function (x, y)
//计算是否是最小宽度
const width, height, isLeftMove, isTopMove = this.getMinSize(this.rectWidth - x, y);
if (isLeftMove)
this.rect.style.left = this.rectOffsetLeft + x + 'px';
this.rect.style.width = width + 'px';
if (isTopMove)
this.rect.style.height = height + 'px';
;
/**
* 移动主矩形缩放 - 右上
*/
CreateDragRect.prototype.neRectSize = function (x, y)
//计算是否是最小宽度
const width, height, isTopMove, isLeftMove = this.getMinSize(x, this.rectHeight - y);
if (isTopMove)
this.rect.style.height = height + 'px';
this.rect.style.top = this.rectOffsetTop + y + 'px';
if (isLeftMove)
this.rect.style.width = width + 'px';
;
/**
* 移动主矩形缩放 - 右下
*/
CreateDragRect.prototype.seRectSize = function (x, y)
//计算是否是最小宽度
const width, height = this.getMinSize(x, y);
this.rect.style.width = width + 'px';
this.rect.style.height = height + 'px';
;
/**
* 节流函数
* @param * fn
* @param * delay
*/
CreateDragRect.prototype.throttle = function (fn, delay)
let last = 0;
return function ()
let curr = Date.now();
if (curr - last > delay)
fn.apply(this, arguments);
last = curr;
/**
* 获取宽高
* @param * w
* @param * h
* @return Object
*/
CreateDragRect.prototype.getMinSize = function (w, h)
let rectMinWidth = this.rectMinWidth;
let rectMinHeight = this.rectMinHeight;
//x拖拽
this.isLeftMove = w >= this.rectMinWidth;
//y拖拽
this.isTopMove = h >= this.rectMinHeight;
if (this.isLeftMove) rectMinWidth = w;
if (this.isTopMove) rectMinHeight = h;
return width: rectMinWidth, height: rectMinHeight, isLeftMove: this.isLeftMove, isTopMove: this.isTopMove ;
三、完整代码
只想用代码功能的,只需要复制到你的html文件中就可以直接使用了.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现拖拽缩放元素(工厂模式)</title>
<style type="text/css">
*
padding: 0;
margin: 0;
#app-warpper
position: absolute;
cursor: move;
</style>
</head>
<body>
<div id="app-warpper"></div>
</body>
<script>
/**
* 创建一个可拖拽的矩形
*/
function CreateDragRect(elm, options = )
if (!elm) throw new Error('el 必须是一个document对象');
this.rect = elm;
this.isLeftMove = true;
this.isTopMove = true;
this.rectDefaultPosition = options.position || 'fixed';
this.rectDefaultLeft = options.x || 0;
this.rectDefaultTop = options.y || 0;
this.rectWidth = options.width || 100;
this.rectHeight = options.height || 100;
this.rectMinWidth = options.rectMinWidth || 5; //最小宽度(超过之后不允许再缩放)
this.rectMinHeight = options.rectMinHeight || 5; //最小高度(超过之后不允许再缩放)
this.rectBackgroundColor = options.background || '#ccc';
this.dragIconSize = options.dragIconSize || '4px';
this.dragIconColor = options.dragIconColor || '#f00';
//主矩形是否可以移动
this.isMove = false;
this.initStyle();
this.bindDragEvent(this.rect);
/**
* 主矩形绑定move事件
*/
CreateDragRect.prototype.bindDragEvent = function (dom, position)
const _this = this;
dom.onmousedown = function (event)
event.stopPropagation();
//按下矩形的时候可以移动,否则不可移动
_this.isMove = !position;
// 获取鼠标在wrapper中的位置
let boxX = event.clientX - dom.offsetLeft;
let boxY = event.clientY - dom.offsetTop;
//鼠标移动事件(如果计算太高,有拖影)
document.onmousemove = _this.t可拖拽bottomsheetviewcontroller(代码片段)
...中,长按拖拽手势可以让controller上滑或者向下消失。实现原理是,通过监听拖拽事件,动态改变view之间的autolayout约束,并加上少许动画。下面看源码:第一个页面ViewController.swi 查看详情
android可拖拽view的简单实现(代码片段)
其实Android可拖拽View实现起来很简单,最简单的就是实现View的setOnTouchListener方法。下面这段代码就实现了如下两个功能:1、View随着手指的拖动儿拖动。2、当松开手指的时候,如果View在屏幕的右半边,则自动让其贴到屏幕右边... 查看详情
android可拖拽view的简单实现(代码片段)
其实Android可拖拽View实现起来很简单,最简单的就是实现View的setOnTouchListener方法。下面这段代码就实现了如下两个功能:1、View随着手指的拖动儿拖动。2、当松开手指的时候,如果View在屏幕的右半边,则自动让其贴到屏幕右边... 查看详情
android自定义view实现可拖拽的进度条
...可,不过这里需要调整文字绘制的垂直的偏移,这样才能实现文字垂直居中实现拖拽需要对onTouchEvent方法进行处理,也就是当手指触摸矩形区域的时候,根据手指横向滑动的偏移来设置当前的进度,具体如下为了适配高度的wrap_c... 查看详情
androidactivity内实现可拖拽悬浮控件(代码片段)
效果图实现方式://在activity中重写此方法@OverrideprotectedvoidonPostCreate(@NullableBundlesavedInstanceState)super.onPostCreate(savedInstanceState);//添加一个悬浮Viewroot=findViewById(android.R.id.content);if(rootinstanceofFrameLayout)FrameLayoutcontent=(Fra... 查看详情
可拖拽bottomsheetviewcontroller(代码片段)
...中,长按拖拽手势可以让controller上滑或者向下消失。实现原理是,通过监听拖拽事件,动态改变view之间的autolayout约束,并加上少许动画。下面看源码:第一个页面ViewController.swift:importUIKitclassViewController:... 查看详情
可拖拽bottomsheetviewcontroller(代码片段)
...中,长按拖拽手势可以让controller上滑或者向下消失。实现原理是,通过监听拖拽事件,动态改变view之间的autolayout约束,并加上少许动画。下面看源码:第一个页面ViewController.swift:importUIKitclassViewController:... 查看详情
vue侧边栏可拖拽,右侧区域可自适应宽度(代码片段)
...可拖拽条,拖拽后左右两边都能自适应宽度查阅相关实现,发现这种方法亲测可用,在此记录一下1.效果显示图效果图1拖拽效果图2.页面代码<template><el-container><el-main><divclass="myBox">&l 查看详情
基于vue+elementui的文件上传(可拖拽上传)(代码片段)
(文章目录)实现效果一、先创建一个Dialog对话框进行存放<template><!--导入遮罩层--><el-dialog:title="$t(to_lead)":visible.sync="BatchAdd"custom-class="BatcchAdd"width="30%":bef 查看详情
element-uitable表格组件实现可拖拽效果(行列)(代码片段)
首先,需要用到第三方库,sortable.js,因为我的项目是vue,所以在package引用的是vuedraggable,而vuedraggable是包含sortable的。npminstallsortable.js--save//或者npmi-Svuedraggable//vuedraggable依赖Sortable.js& 查看详情
编写可拖拽的弹窗(代码片段)
...。虽然拖拽起来不是很流畅,但是也算是满足要求了。1.实现原理主要的实现原理还是获取鼠标在div中的位置,获取位置后设置div的left和top来达到div跟随鼠标移动的效果。因为写的是vue,所以利用了vue的自定义指令来操作dom。2.... 查看详情
android——基于constraintlayout实现的可拖拽位置控件(代码片段)
最近在研究使用android实现平板和电脑端一些应用的效果,话不多说先上个图可以看到,实现了中间的绿色区域换到父布局最左侧的功能。在拖动的过程中,父布局会出现上下左右四个箭头按钮,当光标移动到箭头... 查看详情
js实现可拖拽的div
实现一个div可以被拖拽,代码如下所示:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>zzw_drap</title><style>*{margin:0;padding:0;}#box{position:absolute;top:100 查看详情
鸟哥杂谈十分钟搭建自己的本地node-red可拖拽图形化物联网(代码片段)
忘记过去,超越自己❤️博客主页单片机菜鸟哥,一个野生非专业硬件IOT爱好者❤️❤️本篇创建记录2022-10-16❤️❤️本篇更新记录2022-10-16❤️🎉欢迎关注🔎点赞👍收藏⭐️留言📝🙏此博客均由博... 查看详情
10分钟实现简易vue拖拽排序(代码片段)
背景平平无奇的一天,博主正在敲着自己的项目,这时候被领导告知要我写一个工程自动化工具,接到需求的时候我的大脑便开始疯狂转圈(因为我需要前后端都做,相对来说思考的东西要多一点),后来在思考数据设计,接口数据处... 查看详情
elementui可拖拽dialog-vue2(代码片段)
文章目录1.准备js1.1`dialog-drag.js`1.2`index.js`2.`main.js`引用自定义指令3.使用1.准备js1.1dialog-drag.jsimportVuefrom'vue'/**使用方法*将以下代码复制到一个js文件中,然后在入口文件main.js中import引入即可; 查看详情
android高级控件——自定义listview高仿一个qq可拖拽列表的实现
...级控件(六)——自定义ListView高仿一个QQ可拖拽列表的实现我们做一些好友列表或者商品列表的时候,居多的需求可能就是需要列表拖拽了,而我们选择了ListView,也是因为使用ListView太久远了,导致对他已经有浓厚的感情了,... 查看详情
可拖拽圆形进度条组件(支持移动端)(代码片段)
.katexdisplay:block;text-align:center;white-space:nowrap;.katex-display>.katex>.katex-htmldisplay:block;.katex-display>.katex>.katex-html>.tagposition:absolute;right:0px;.katexfont:1.21em/1.2Ka 查看详情