使用JS制作一个鼠标可拖的DIV(三)——移动带图片DIV
当DIV元素里,存在图片元素的时候,会使拖动出现异常。
因为图片元素本身就支持拖动,所以,只要在图片标签加入:draggable='false'。
如下:
<div onmousedown="moveBind(this, event)" style="width:50px;height:50px; left:285px;top:370px; position:absolute;"><img src="http://pic.cnitblog.com/face/614265/20140725231849.png" draggable="false"></div>
增加动态增加元素:
var containerId = "innerContainer"; var showId = "idShow"; var moveElement = "div"; function addElement(obj) { var img = "<" + obj.tagName + " src='" + obj.src + "' draggable='false' />"; var container = findPosition(document.getElementById(containerId)); var containerLeft = container[0]; var containerTop = container[1]; var containerWidth = container[4]; var containerHeight = container[5]; var left = containerLeft + containerWidth / 2 - obj.offsetWidth / 2; var top = containerTop + containerHeight / 2 - obj.offsetHeight / 2; $("#" + containerId).append("<div onmousedown='moveBind(this, event)' style='width:" + obj.offsetWidth + "px;height:" + obj.offsetHeight + "px; left:" + left + "px;top:" + top + "px; position:absolute;'>" + img + "</div>"); }
<div> <img src="http://pic.cnitblog.com/face/614265/20140725231849.png" style="width:50px; height: 50px;" onclick="addElement(this)" /> </div>