san*_*a B 5 javascript move zooming pan drag
我正在编写一个小脚本,使对象(div 或 img)在给定框架内可移动和缩放。
但是,我遇到了一些我不太确定的问题,因为我是 javascript 初学者-因此将不胜感激解释为什么会出现这些问题。
问题:
start_drag(),while_drag()然后stop_drag()返回undefined- 为什么会这样?应该返回什么?mousedown事件绑定到图像。我做错了什么?请看我的小提琴:https : //jsfiddle.net/pow4ngbw/15/
现在工作正常,主要是图像 css 但发现了几个错误(请参阅新的 img 属性),还添加了一些调整以使拖动更平滑。
var img_ele = null,
x_cursor = 0,
y_cursor = 0,
x_img_ele = 0,
y_img_ele = 0;
function zoom(zoomincrement) {
img_ele = document.getElementById('drag-img');
var pre_width = img_ele.getBoundingClientRect().width, pre_height = img_ele.getBoundingClientRect().height;
img_ele.style.width = (pre_width * zoomincrement) + 'px';
img_ele.style.height = (pre_height * zoomincrement) + 'px';
img_ele = null;
}
document.getElementById('zoomout').addEventListener('click', function() {
zoom(0.5);
});
document.getElementById('zoomin').addEventListener('click', function() {
zoom(1.5);
});
function start_drag() {
img_ele = this;
x_img_ele = window.event.clientX - document.getElementById('drag-img').offsetLeft;
y_img_ele = window.event.clientY - document.getElementById('drag-img').offsetTop;
}
function stop_drag() {
img_ele = null;
}
function while_drag() {
var x_cursor = window.event.clientX;
var y_cursor = window.event.clientY;
if (img_ele !== null) {
img_ele.style.left = (x_cursor - x_img_ele) + 'px';
img_ele.style.top = ( window.event.clientY - y_img_ele) + 'px';
console.log(img_ele.style.left+' - '+img_ele.style.top);
}
}
document.getElementById('drag-img').addEventListener('mousedown', start_drag);
document.getElementById('container').addEventListener('mousemove', while_drag);
document.getElementById('container').addEventListener('mouseup', stop_drag);Run Code Online (Sandbox Code Playgroud)
#drag-img {
cursor: move;
position: relative;
width: 500px;
height: 500px;
}
#container {
overflow: hidden;
background: red;
height: 500px;
width: 500px;
}
.button {
width: 200px;
height: 50px;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<img ondragstart="return false" id="drag-img" src="http://www.patsoy.com/p/2015/09/geometric-patterns-f03phtdx.jpg" />
</div>
<input type="button" id="zoomout" class="button" value="Zoom out">
<input type="button" id="zoomin" class="button" value="Zoom in">
Run Code Online (Sandbox Code Playgroud)