我发现 theZillion ( http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery/ ) 的这个脚本使 div 可拖动。我正在尝试使用此脚本按类名移动 div。而且不是通过 ID。
我有一个可以工作的事件处理程序,但在添加脚本时却不能...控制台也没有显示任何错误。关于如何实现这项工作有什么想法吗?
这是我的代码:
function wrappmover(){
var moveEvent = "dice-window-wrapper";
var addClassArr= document.getElementsByClassName(moveEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", movewrapp, true);
}
function movewrapp() {
var classToMove = "dice-window-wrapper";
var elems = document.getElementsByClassName(classToMove);
var tzdragg = function(){
return {
startMoving : function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
a = document.getElementsByClassName(classToMove),
divTop = a.style.top,
divLeft = a.style.left;
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
tzdragg.move('elem',aX,aY);
}
},
stopMoving : function(){
document.onmousemove = function(){}
},
move : function(divid,xpos,ypos){
var a = document.getElementById(divid);
document.getElementById(divid).style.left = xpos + 'px';
document.getElementById(divid).style.top = ypos + 'px';
}
}
}();
最佳答案
好的,那么您想在页面上添加可拖动的元素吗?
看一下下面的代码(这里是 a working example )。我希望您会发现它是不言自明的,但以防万一还有评论:
// Wrap the module in a self-executing anonymous function
// to avoid leaking variables into global scope:
(function (document) {
// Enable ECMAScript 5 strict mode within this function:
'use strict';
// Obtain a node list of all elements that have class="draggable":
var draggable = document.getElementsByClassName('draggable'),
draggableCount = draggable.length, // cache the length
i; // iterator placeholder
// This function initializes the drag of an element where an
// event ("mousedown") has occurred:
function startDrag(evt) {
// The element's position is based on its top left corner,
// but the mouse coordinates are inside of it, so we need
// to calculate the positioning difference:
var diffX = evt.clientX - this.offsetLeft,
diffY = evt.clientY - this.offsetTop,
that = this; // "this" refers to the current element,
// let's keep it in cache for later use.
// moveAlong places the current element (referenced by "that")
// according to the current cursor position:
function moveAlong(evt) {
that.style.left = (evt.clientX - diffX) + 'px';
that.style.top = (evt.clientY - diffY) + 'px';
}
// stopDrag removes event listeners from the element,
// thus stopping the drag:
function stopDrag() {
document.removeEventListener('mousemove', moveAlong);
document.removeEventListener('mouseup', stopDrag);
}
document.addEventListener('mouseup', stopDrag);
document.addEventListener('mousemove', moveAlong);
}
// Now that all the variables and functions are created,
// we can go on and make the elements draggable by assigning
// a "startDrag" function to a "mousedown" event that occurs
// on those elements:
for (i = 0; i < draggableCount; i += 1) {
draggable[i].addEventListener('mousedown', startDrag);
}
}(document));
将其装入或包裹在 <script></script>
中标签 as close as possible to </body>
这样就不会阻止浏览器获取其他资源。
其实,如果把注释去掉的话,这是一个很小的功能。比您提供的网站上的小得多且效率更高。
可能的改进
考虑用 makeDraggable(selector);
之类的内容替换匿名包装器哪里selector
是 CSS selector ,这样你就可以做一些疯狂的事情,比如:
makeDraggable('#dragMe, #dragMeToo, .draggable, li:nth-child(2n+1)');
可以通过使用 document.querySelectorAll
来实现能够执行复杂的 CSS 查询,而不是简单的类名查找 document.getElementsByClassName
.
需要注意的事项
- 如果页面有任何滚动 - 拖动看起来会被破坏;考虑通过 scrollX and scrollY 调整拖动元素的位置
- 这显然在 Internet Explorer 中不起作用(请自行解决)。
- 可能存在内存泄漏(需要分析和测试)。
编辑:添加新的可拖动元素的解决方案
那么您希望能够添加更多可拖动元素吗?有几种方法可以解决这个问题。例如,您可以写 makeDraggable(element);
函数并在要添加到 DOM 的元素上调用它。它当然会起作用,但是让我们看看一些不同的东西,好吗?
我们为什么不为文档正文上的“mousedown”事件分配一个,而不是查询 DOM 来搜索可拖动元素并为其分配事件监听器。
触发时,事件对象将包含对 target element 的引用这是已调度事件的对象(您按下鼠标的元素)。代码的相关部分现在类似于:
// Performs a check if the current element is draggable and if yes,
// then the dragging is initiated:
function startDragIfDraggable(evt) {
// Check if the target element (referenced by evt.target) contains a
// class named "draggable" (http://stackoverflow.com/questions/5898656/):
if (evt.target.classList.contains('draggable')) {
// Invoke startDrag by passing it the target element as "this":
startDrag.call(evt.target, evt);
}
}
// Listen for any "mousedown" event on the document.body and attempt dragging
// the target element (the one where "mousedown" occurred) if it's draggable:
document.body.addEventListener('mousedown', startDragIfDraggable);
这是a working example上面的代码。作为奖励,它具有模拟向 DOM 添加新的可拖动元素的功能。
除了能够拖动动态添加的可拖动元素之外,这种方法还将节省一些内存,因为我们现在可以避免将一堆事件监听器分配给一堆元素。但是,如果您正在开发的应用程序是点击密集型的(例如游戏),那么您可能会因为每次点击的检查而浪费一点 CPU。
关于javascript - 带有 className 的可拖动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695933/