简体   繁体   English

div元素的拖放

[英]drag&drop of div element

I have a rectangular div element on a page with image and text span inside. 我的页面上有一个矩形div元素,其中包含图像和文本。 Div has 2px border to make it actually visible. Div具有2px边框,以使其实际可见。

Then I add dragstart event listener to my div element. 然后,将dragstart事件侦听器添加到div元素。 dragstart event fires always if I start dragging the image inside div but it is very problematic if I start dragging by clicking on text span or blank place: 如果我开始在div内拖动图像,总是会启动dragstart事件,但是如果我通过单击文本范围或空白位置开始拖动,则会很成问题:

In Google Chrome dragging is very unstable. 在Google Chrome浏览器中,拖动非常不稳定。 It can work a few times then stops firing, then work again and so on. 它可以工作几次,然后停止发射,然后再次工作,依此类推。 In Mozilla Firefox it doesn't work at all. 在Mozilla Firefox中,它根本不起作用。

How to fix it and allow drag by clicking on any point inside bound rect of my div? 如何修复它并通过单击div绑定矩形内的任何点来允许拖动?

<div class="item">
  <img src="https://www.wigwam3d.com/previews/1f/1ffbf8da-a4d0-4e40-b9e1-0329220969dc.jpg">
  <div>Element</div>
</div>

Plunker: http://plnkr.co/edit/673ytif50cViE5dTv3df?p=preview 柱塞: http ://plnkr.co/edit/673ytif50cViE5dTv3df?p=preview

Use this code , you can drag div anywhere on the window. 使用此代码,您可以将div拖动到窗口的任何位置。 Also fix width and height of the div. 还要固定div的宽度和高度。

$(function(){ $("#animation").css({"cursor":"move"}) $(function(){$(“#animation”)。css({“ cursor”:“ move”})

// mousedown:fn(){dragging = true;}


var dragging = false;
var iX, iY;
$("#animation").mousedown(function(e) {
    dragging = true;
    iX = e.clientX - this.offsetLeft;
    iY = e.clientY - this.offsetTop;
    this.setCapture && this.setCapture();
    return false;
});

// mouseover:fn(){dragging = tru;}

document.onmousemove = function(e) {
    if (dragging) {
        var e = e || window.event;
        var oX = e.clientX - iX;
        var oY = e.clientY - iY;
        $("#animation").css({"left":oX + "px", "top":oY + "px"});
        return false;
    }
};

// mouseup:fn(){dragging = false;} // mouseup:fn(){dragging = false;}

$('#animation').mouseup(function(e) {
    dragging = false;
    this.releaseCapture && this.releaseCapture();
    e.cancelBubble = true;
})

}) })

Just found a simple solution: add attribute draggable=true on div element! 刚刚找到了一个简单的解决方案:在div元素上添加属性draggable = true! That's all! 就这样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM