有没有办法让我的网站使用右键单击按钮拖动DOM元素?根据{{3}} MDN参考,drag
事件具有buttons
属性,左键单击为1,右键单击为2,两者均为3。所以我写了一些非常简单的东西来测试:
data:text/html, <div id="draggable" draggable="true" ondrag="console.log(event.buttons)" oncontextmenu="return false">Drag This</div>
当我使用左键拖动此div时,它会向控制台输出1(重复,因为ondrag
事件在拖动过程中不断触发)。当我尝试用右键拖动时,没有任何反应 - 我无法拖动它。当我开始用左按钮拖动它,然后按住左右按钮,它会打印3.如果我这样做然后释放左按钮并且只按住右按钮,则拖动会立即结束。
有没有办法允许使用鼠标右键拖动元素?
(如果重要的话,我正在使用最新的Chrome稳定版。)
答案 0 :(得分:2)
我正在使用此代码并为我工作。
左右两边都可以拖动以拖动div。
dragDiv.onmousedown = function(e) {
var shiftX = e.clientX - dragDiv.getBoundingClientRect().left;
var shiftY = e.clientY - dragDiv.getBoundingClientRect().top;
dragDiv.style.position = 'absolute';
dragDiv.style.zIndex = 1000;
document.body.append(dragDiv);
moveDiv(e.pageX, e.pageY);
function moveDiv(pageX, pageY) {
dragDiv.style.left = pageX - shiftX + 'px';
dragDiv.style.top = pageY - shiftY + 'px';
}
function onMouseMoveDiv(e) {
moveDiv(e.pageX, e.pageY);
}
document.addEventListener('mousemove', onMouseMoveDiv);
dragDiv.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMoveDiv);
dragDiv.onmouseup = null;
};
};
dragDiv.ondragstart = function() {
return false;
};
body
{
padding:10px;
}
#dragDiv
{
height:15px;
width:15px;
border:15px solid black;
background:blue;
}
<html>
<head>
<title>Drag Div using Right or Left Mouse Click.</title>
</head>
<body>
<p>Drag Div using Right or Left Mouse Click.</p>
<div id="dragDiv"></div>
</body>
</html>