[英]How to make a draggable image in div?
I am trying to move a image in a div like a facebook cover page, but it is not moving smoothly with image tag 我正在尝试在像Facebook封面这样的div中移动图像,但是使用图像标签时它无法平稳移动 . 。 when I put this image in a div like a background image it is working my js code is .. 当我将此图像放在像背景图像这样的div中时,它在工作,我的js代码是..
var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
var ele = document.getElementById('ele');
var width = 400-ele.clientWidth;
var height = 400-ele.clientHeight;
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
});
}
function init() {
var ele = document.getElementById('ele');
draggable(ele);
}
and my html code which is not working is.. 和我的HTML代码是行不通的..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<img src="Desert.jpg" id="ele" style="position:absolute;"></img>
</div>
</body>
and this code is working.. 并且此代码正在工作..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<div id="ele" style="width:100%; height:100%; background-color: gray; position:absolute; background-image:url( 'Desert.jpg' );"></div>
</div>
</body>
You could refer to this question, which handles the same idea of dragging images, althought the question is slightly different. 您可以参考这个问题,该问题处理拖动图像的想法相同,尽管问题略有不同。 Check out his/her JSFiddle from question. 从问题中查看他/她的JSFiddle。
<img>
is a self-closing tag. <img>
是一个自动关闭的标签。 You don't need the </img>
as it's not valid. 您不需要</img>
因为它无效。 Remove that and it should work fine. 删除它,它应该可以正常工作。 Depending on your doctype
you should use: 根据您的doctype
您应该使用:
HTML5 HTML5
<img src="Desert.jpg" id="ele" style="position:absolute;">
XHTML (note the /
at the end of the tag) XHTML (注意标记末尾的/
)
<img src="Desert.jpg" id="ele" style="position:absolute;" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.