javascript - 如何使用 Vanilla JS 拖放 select -option 元素
问题描述
我最近尝试在选择元素中拖动选项框内容。似乎无法完成 - 拖动根本不会触发。我考虑完全重新设计这个元素,让它看起来像 Select。此处描述了 jQuery 的其他选项: https : //stackoverflow.com/questions/ask 在我的情况下,它必须使用 Vanilla.JS 完成。我当然可以对上面的代码进行反向工程,但是也许有人知道其他可行的解决方案?
解决方案
使您希望拖动的元素成为绝对元素并将其放置在使用z-index
. 然后获取元素的x
和y
坐标。将元素直接移动到正文中,将元素放在指针的中心。添加事件侦听器以mousemove
使用函数将元素置于页面x
/y
坐标的中心。释放鼠标按钮时删除元素的功能.onmouseup
,这将删除与元素移动相关的所有事件侦听器。
注意: 这是非常基本的,如果用户将元素拖出页面边界,则必须使用更多代码来确定页面约束。
let drag = document.getElementById('draggableSpan');
drag.onmousedown = function(event) {
// make element absolute and place it on top with z-index
drag.style.position = 'absolute';
drag.style.zIndex = 1000;
let shiftX = event.clientX - drag.getBoundingClientRect().left;
let shiftY = event.clientY - drag.getBoundingClientRect().top;
// move it out of any current parents directly into body
// to make it positioned relative to the body
document.body.append(drag);
// function that centers the element at (pageX, pageY) coordinates
function moveTo(pageX, pageY) {
drag.style.left = pageX - shiftX + 'px';
drag.style.top = pageY - shiftY + 'px';
}
// move the absolutely positioned element under the pointer
moveTo(event.pageX, event.pageY);
function onMouseMove(event) {
moveTo(event.pageX, event.pageY);
}
// move the element on mousemove with event listener
document.addEventListener('mousemove', onMouseMove);
// drop the element on the page by removing eventlisteners that
// are relavent to the moving of the element
drag.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMove);
drag.onmouseup = null;
};
};
<div class='parent'>
<span id='draggableSpan'>
draggable
</span>
</div>
推荐阅读
- c++ - 数学导师计划的烦恼
- javascript - 在叠加图像下绘制新路径
- ruby-on-rails - Rails 模型关联 - has_one 还是单表继承?
- android - 将脚本添加到 AOSP
- css - 使用 Bulma 为 Vue 中的活动链接设置样式
- javascript - 无法在 JavaScript 上创建滚动效果
- html - 边距右:自动和边距左:自动不工作
- python - 如何将aws glue的python shell连接到oracle数据库
- google-apps-script - Google Apps 脚本幻灯片向形状添加阴影
- git - Git 合并冲突已解决,没有要提交的更改