如何用js实现一个拖拽效果
这篇文章主要介绍“如何用js实现一个拖拽效果”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何用js实现一个拖拽效果”文章能帮助大家解决问题。
.markdown-body{word-break:break-word;line-height:1.75;font-weight:400;font-size:15px;overflow-x:hidden;color:#333}.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6,.markdown-body h7{line-height:1.5;margin:30px 0 10px;color:#cca152;position:relative;padding-left:50px;border-bottom:2px solid rgba(209,163,78,.6);padding-bottom:0}.markdown-body h2{font-size:30px}.markdown-body h2:before{content:"";width:50px;height:42px;display:block;position:absolute;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAhBAMAAACo1K8bAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CkzCJ1kAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAnUExURUdwTMyhUsqkUMyhUsyiUcyhUsyhUsyhUcyhUsyhUs2hUtytWNWoVX44si8AAAAKdFJOUwD8Bfcge95QncCWSSDAAAABh0lEQVQoz2WSPUvDQBjHjyPSOB7drh3OUOs36NA6pKAFwaEo4tDFIUWxGYLgKw4BEYUuHaQg7XJ0kccsUmrT2qUUQZp8KO/y1hSfIYEf/5eHu0MoGU1+sIbSw5Bypd92S+dWWrd34b15vuOPY4QxuvtYZp0lIVk3Zgjt+5zkh22AvBHnbW85BOjXySPwhc5CYcY0OdDh6dEUqIEj4cN8Dty3a1MqYJS4MaWU5wzVLwMMxqGSNQgA/VFa4gf50yhxSUW+db8ACa2gBxfnABVDFYHCPYrc7TLwCepJM8/ZoVsRwpxdHEozHUXd6idwVzFFM5BFmIhQVQjrNdnCvdd48wblI2VHtsAZioSsTYVwLoXvjMXH1icuNgPhQE+Ot1+xi8HeA3d1Df1f1JPVUOmsYLujBjuSySqSXYt+yTwbJ0pcyIhqTrxkn0BazRLizJosxRBued+z0jPD6VewOXl5utHRGmMNK3k0iTkzxpq2/oIQO6gLprF12kT/R20eyzlcg7iwK0dPsz/ibpdsCHweWwAAAABJRU5ErkJggg==) 0 0 no-repeat;background-size:80%;bottom:-10px;left:-2px}.markdown-body h3{font-size:24px}.markdown-body h3:before{content:"";width:50px;height:42px;display:block;position:absolute;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAhBAMAAACo1K8bAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CkzCJ1kAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAnUExURUdwTMyhUsqkUMyhUsyiUcyhUsyhUsyhUcyhUsyhUs2hUtytWNWoVX44si8AAAAKdFJOUwD8Bfcge95QncCWSSDAAAABh0lEQVQoz2WSPUvDQBjHjyPSOB7drh3OUOs36NA6pKAFwaEo4tDFIUWxGYLgKw4BEYUuHaQg7XJ0kccsUmrT2qUUQZp8KO/y1hSfIYEf/5eHu0MoGU1+sIbSw5Bypd92S+dWWrd34b15vuOPY4QxuvtYZp0lIVk3Zgjt+5zkh22AvBHnbW85BOjXySPwhc5CYcY0OdDh6dEUqIEj4cN8Dty3a1MqYJS4MaWU5wzVLwMMxqGSNQgA/VFa4gf50yhxSUW+db8ACa2gBxfnABVDFYHCPYrc7TLwCepJM8/ZoVsRwpxdHEozHUXd6idwVzFFM5BFmIhQVQjrNdnCvdd48wblI2VHtsAZioSsTYVwLoXvjMXH1icuNgPhQE+Ot1+xi8HeA3d1Df1f1JPVUOmsYLujBjuSySqSXYt+yTwbJ0pcyIhqTrxkn0BazRLizJosxRBued+z0jPD6VewOXl5utHRGmMNK3k0iTkzxpq2/oIQO6gLprF12kT/R20eyzlcg7iwK0dPsz/ibpdsCHweWwAAAABJRU5ErkJggg==) 0 0 no-repeat;background-size:70%;bottom:-15px;left:-1px}.markdown-body h4{font-size:18px}.markdown-body h4:before{content:"";width:50px;height:42px;display:block;position:absolute;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAhBAMAAACo1K8bAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ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.markdown-body h5{font-size:16px;padding-left:0;border-bottom:1px solid rgba(209,163,78,.6)}.markdown-body h6{font-size:15px;padding-left:0}.markdown-body em{color:#cca152}.markdown-body del{text-decoration-color:#cca152;text-decoration-thickness:2px}.markdown-body p{line-height:inherit;margin-top:22px;margin-bottom:22px}.markdown-body img{max-width:80%;margin:6px auto;box-shadow:0 6px 15px #8e8e8e;display:block;margin:20px auto!important;object-fit:contain;border-radius:8px}.markdown-body hr{border:none;border-top:2px solid #e0c9a1;margin-top:32px 0}.markdown-body code{word-break:break-word;border-radius:2px;overflow-x:auto;background:#f6efde;color:#b69454;font-size:.87em;padding:.065em .4em}.markdown-body code,.markdown-body pre{font-family:Mono,Menlo,Monaco,Consolas,Courier New,monospace}.markdown-body pre{overflow:auto;position:relative;line-height:1.75;background:#fef6e1;border-radius:4px;box-shadow:0 0 8px hsla(0,0%,47%,.45)}.markdown-body pre:before{content:"";display:block;height:30px;width:100%;margin-bottom:-7px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAOCAMAAABaWb9VAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CkzCJ1kAAAAJcEhZcwAADsQAAA7EAZUrDhsAAACHUExURUdwTMxCKdc8NvdYT/9hVyLJPABBAGubKNiIOv+/K+ytJBakH9aZG+5QR5VZDOBDPhmtJ8+VGuGjH/CwJR26MR6+NBq0LPW1KBmwKetNRfJUTONHP92fHuSmIeFEPhu3LR29M/BTS+mqIuqsI5qdHyLKPP++Kv9gVf9lW//KLSXXQCTQP//FLMVm5KQAAAAldFJOUwAlPPz7+woBBPu8Mzu+FlRRKmvnweeG+Wqg6mVNXmuc1OCbmjZJWF/9AAABKklEQVQoz3WS6XaCMBCFRzAM++KGsqhtDwES3//5OtmA2uP9A9zwzRoAgBC0QgQrdA68OZsDr229YGHoIEj7Pl0ZOgjKa5lYJ4Rd1vijn3nuD4Qurjmv48o6RFyfbGDnS6DeEXZfk5ZfuBhdPb9I87ECNMh2EFJKIU6agWzaa01NbmLkxznSmmObJBkkUxrERf3i+ftRiZi7ShPCYY64UhTx1AR5CDYoMXkOKEY7GmTcTzeD/FiER68DfSLgSRqEIBoB3P8h4x8RZhBXGJGusJdD6rfCBl0YqvZNkrV9zej2cWlfJWG6fRpyM41qYH+GTPPi2yFLQYC0Qybm5o96lW77kMbcrBKtgeWTsthVamNXFF4I6x0DTPuugsVRFyYpyxzWqNvHJwed8ws7QyP1UwjNjwAAAABJRU5ErkJggg==) 10px 10px no-repeat;background-size:40px}.markdown-body pre>code{font-size:12px;padding:15px 12px;margin:0;word-break:normal;display:block;overflow-x:auto;color:#333;background:#fef6e1}.markdown-body a{text-decoration:none;color:#d8ac5a;border-bottom:1px solid #d8ac5a}.markdown-body a:active,.markdown-body a:hover{color:#93753f;border-color:#93753f}.markdown-body table{display:inline-block!important;font-size:12px;width:auto;max-width:100%;overflow:auto;border:1px solid #f4e8c7;border-collapse:collapse}.markdown-body thead{background:rgba(255,227,176,.6588235294);text-align:left;display:table-header-group;border-bottom:1px solid rgba(255,227,176,.6588235294)}.markdown-body tbody{background:rgba(255,247,229,.3882352941)}.markdown-body td,.markdown-body th{padding:7px;line-height:24px;min-width:100px}.markdown-body blockquote{color:#bd954f;padding:1px 23px;margin:22px 0;border-left:4px solid #dcb267;background-color:#fff7e5}.markdown-body blockquote:after{display:block;content:""}.markdown-body blockquote>p{margin:10px 0}.markdown-body ol,.markdown-body ul{padding-left:28px}.markdown-body ol .task-list-item,.markdown-body ul .task-list-item{list-style:none}.markdown-body ol li{padding-left:6px}.markdown-body::marker{color:#dcb267}.markdown-body .contains-task-list{padding-left:0}.markdown-body .contains-task-list .task-list-item{list-style:none;position:relative}.markdown-body .contains-task-list .task-list-item input[type=checkbox]{position:relative;top:2px}.markdown-body .contains-task-list .task-list-item input[type=checkbox]:before{content:"";display:inline-block;height:12px;width:12px;position:absolute;left:-2px;top:-2px;border:2px solid #cda152;border-radius:5px}.markdown-body .contains-task-list .task-list-item input[type=checkbox]:checked{position:relative;top:2px}.markdown-body .contains-task-list .task-list-item input[type=checkbox]:checked:before{border:none;content:"";display:inline-block;height:17px;width:17px;position:absolute;left:-2px;top:-2px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M/3AAAAAXNSR0IArs4c6QAAAYhJREFUOBFjYACC0/MDGsDEiyvr/zOCeUwMJxn/A8HZRUEMYBFGJsZ6kFoQYALiAyAGCgDpA+sFijKeWRj4H1kWpIWBW1SDQcm+BCzOAiK/vr7BcO/gDbAAI4hE1waWgRBnmWCGIwkyKFjnwow0BhsJk9QLncvw5dV1oPE9MCEGmBWrgCKhcFEowyR+PSNYwemFAZ4M/xjMkRWYJm5oAPFB/joDpI1BHHQANgGPDxj+//vfCA4IdJ3GcevgQnAFhlHLwYIgSVA0wABcwY3tFQzokiBFGIEP0wmigW5wZAK5FFkQib0a6NUDcEmgb7AGFpIGZOZqoMFhIAFQknEAJpn9yLLEssFOBCp2IFaDkl0xg6C8FbJyB3gowUS5RdQYBORQYpVB1iwVHIIMwJh///AYTCmYRklNIBFmNi4GeYt0BhnjeIa3dw8wSBlEgDUhxw2yCRgGfHp2geHiqiSwUwUVrFAiFVkjjA1LrjgTHEwhFvosMCZM4NEIUoAtWWNoBGZ70/gN22HiAD2uhAzsYNBZAAAAAElFTkSuQmCC) 0 0 no-repeat;background-size:100%}@media (max-width:720px){.markdown-body h2{font-size:24px}.markdown-body h3{font-size:20px}.markdown-body h4{font-size:18px}} .hljs-comment,.hljs-quote{color:#7d7a68}.hljs-attribute,.hljs-link,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#d73737}.hljs-built_in,.hljs-builtin-name,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#b65611}.hljs-bullet,.hljs-string,.hljs-symbol{color:#60ac39}.hljs-section,.hljs-title{color:#6684e1}.hljs-keyword,.hljs-selector-tag{color:#b854d4}.markdown-body pre,.markdown-body pre>code.hljs{background:#fefbec;color:#6e6b5e}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}
准备
这里我们要用到字体图标,所以我们从iconfont阿里图标库直接引入
找到需要的图标,添加进项目
找到图标所在的项目,点击查看链接
复制地址,或者点击地址复制跳转后地址链接
<link rel="stylesheet" href="https://at.alicdn.com/t/c/font_2579455_c6xlnvkj0j.cssspm=a313x.7781069.1998910419.53&file=font_2579455_c6xlnvkj0j.css">复制代码
创建所需要结构
把我们需要结构先写出来
draggable
:让盒子可以进行拖拽style="--color:#e63e31"
--color让盒子背景色根据--color显示(与下方css样式相联系)
<div class="list"> <div class="list-item" draggable="true" style="--color:#e63e31">
<i class="iconfont icon-shuangyuzuo constellation"></i>
<span class="list-item-title">双鱼座</span>
</div>
<div class="list-item" draggable="true" style="--color:#70d265">
<i class="iconfont icon-shuipingzuo constellation"></i>
<span class="list-item-title">水平座</span>
</div>
<div class="list-item" draggable="true" style="--color:#f0e941">
<i class="iconfont icon-mojiezuo constellation"></i>
<span class="list-item-title">摩羯座</span>
</div>
<div class="list-item" draggable="true" style="--color:#da8218">
<i class="iconfont icon-chunvzuo constellation"></i>
<span class="list-item-title">处女座</span>
</div>
<div class="list-item" draggable="true" style="--color:#7ff0ec">
<i class="iconfont icon-shizizuo constellation"></i>
<span class="list-item-title">狮子座</span>
</div>
</div>复制代码
编写样式
这里直接采用flex对盒子进行排版布局
background-color: var(--color);
var(--color)是或者自定义属性的颜色
body{
background-color: #000;
}
.list{ width: 300px; height: 360px; /* padding: 20px 0; */
margin: 100px auto 0; display: flex;
flex-direction: column;
justify-content: space-around;
}
.list-item{ width: 100%; display: flex;
align-items: center; padding: 0 16px;
border-radius: 10px; /* margin-bottom: 20px; */background-color: var(--color);
}
.constellation{
line-height: 2.5em;
font-size: 20px; color: #fff;
}
.list-item-img{ width: 30px; height: 30px;
}
.list-item-title{
margin-left: 20px; color: #fff;
}// 移动动画class.list-item.moving{
background-color: transparent;border: 2px dashed #ccc;
}复制代码
js编写拖拽效果
首先获取需要用到的元素
// 获取整个listconst list = document.querySelector('.list')// 获取每一个盒子const item = document.querySelectorAll('.list-item')复制代码
开始拖动的时候需要加上移动的类,并且设置移动效果
// 开始拖动
list.ondragstart = e => {
source_node = e.target
recode(item) setTimeout(() => { // 拖拽时样式
e.target.classList.add('moving')
}, 0) // 设置拖动效果
e.dataTransfer.effectAllowed = 'move'
}复制代码
拖拽中需要判断是从上往下还是从下往上,根据拖拽元素和放入元素的索引进行比对,从而对拖拽元素进行插入节点操作
注意: 在码上掘金从上往下的时候会出现bug,在浏览器不会,我个人觉得应该是是码上掘金的问题
// 拖拽放入有效目标触发
list.ondragenter = e => {
e.preventDefault() console.log(e.target.id, list) if (e.target === list || e.target === source_node) { return false
} const childer = Array.from(list.children) const sourceIndex = childer.indexOf(source_node) const targetIndex = childer.indexOf(e.target) // console.log(sourceIndex, targetIndex)
if (sourceIndex < targetIndex) { // 从下往上拖动
list.insertBefore(source_node, e.target.nextElementSibling)
} else { // 从上往下拖动
list.insertBefore(source_node, e.target)
} // 动画效果函数
last([e.target, source_node])
}复制代码
拖拽结束后把拖拽时的样式移除
// 拖放结束
list.ondragend = e => {
e.target.classList.remove('moving')
}复制代码
解释方法
这里有好多没有用过或者比较少用的方法,这里给大家解释一下
ondragstart
:当用户开始拖动一个元素或文本选择时,会触发dragstart事件ondragover
:当元素或文本选择被拖到有效的拖放目标上时(每几百毫秒一次),就会触发拖放事件ondragenter
:当被拖动的元素或文本选择进入有效的拖放目标时,会触发dragenter事件ondragend
: 当拖放操作结束时(通过释放鼠标按钮或点击escape键)触发dragend事件。e.dataTransfer.effectAllowed
:用于设置拖放时的效果,常用参数有(move,link,copy)getBoundingClientRect
:返回元素对于视口的信息requestAnimationFrame
:重绘动画cancelAnimationFrame
:用于取消requestAnimationFrame调用请求
关于“如何用js实现一个拖拽效果”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注蜗牛博客行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
评论