Mit*_*nar 0 javascript javascript-events
我想使用'鼠标拖动'在框内拖动背景的位置.
css:
.filmmakers #map {
width : 920px;
height : 500px;
margin-top : 50px;
margin-left : 38px;
border : 1px solid rgb(0, 0, 0);
cursor : move;
overflow : hidden;
background-image : url('WorldMap.png');
background-repeat : no-repeat;
}
Run Code Online (Sandbox Code Playgroud)
html:
<div id = "map" src = "WorldMap.png" onmousedown = "MouseMove(this)"> </div>
Run Code Online (Sandbox Code Playgroud)
javascript:
function MouseMove (e) {
var x = e.clientX;
var y = e.clientY;
e.style.backgroundPositionX = x + 'px';
e.style.backgroundPositionY = y + 'px';
e.style.cursor = "move";
}
Run Code Online (Sandbox Code Playgroud)
什么都没有发生,没有错误,没有警告,什么都没有......我尝试了很多东西:div内部的绝对定位图像(你可以猜到为什么不起作用),一个带有背景图像的div内的可拖动div,一个拖放的表,最后我尝试了这个:
function MouseMove () {
e.style.backgroundPositionX = 10 + 'px';
e.style.backgroundPositionY = 10 + 'px';
e.style.cursor = "move";
}
Run Code Online (Sandbox Code Playgroud)
这有效,但它与鼠标的位置无关,pageX和pageY也不起作用.
现场演示:http://jsfiddle.net/VRvUB/224/
PS:不管你的想法是什么,请不要用JQuery编写
干杯!
Mithos
根据您的问题,我了解您需要帮助实现实际的"拖动"行为.我猜不会.无论如何,这是我努力的结果:http://jsfiddle.net/joplomacedo/VRvUB/236/
拖动只发生在鼠标按钮上,而且......好吧,它表现得像我想你想要的那样.如果你没有=)只是看小提琴
以下是想要在此处查看的人的代码:
var AttachDragTo = (function () {
var _AttachDragTo = function (el) {
this.el = el;
this.mouse_is_down = false;
this.init();
};
_AttachDragTo.prototype = {
onMousemove: function (e) {
if ( !this.mouse_is_down ) return;
var tg = e.target,
x = e.clientX,
y = e.clientY;
tg.style.backgroundPositionX = x - this.origin_x + this.origin_bg_pos_x + 'px';
tg.style.backgroundPositionY = y - this.origin_y + this.origin_bg_pos_y + 'px';
},
onMousedown: function(e) {
this.mouse_is_down = true;
this.origin_x = e.clientX;
this.origin_y = e.clientY;
},
onMouseup: function(e) {
var tg = e.target,
styles = getComputedStyle(tg);
this.mouse_is_down = false;
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
},
init: function () {
var styles = getComputedStyle(this.el);
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
//attach events
this.el.addEventListener('mousedown', this.onMousedown.bind(this), false);
this.el.addEventListener('mouseup', this.onMouseup.bind(this), false);
this.el.addEventListener('mousemove', this.onMousemove.bind(this), false);
}
};
return function ( el ) {
new _AttachDragTo(el);
};
})();
/*** IMPLEMENTATION ***/
//1. Get your element.
var map = document.getElementById('map');
//2. Attach the drag.
AttachDragTo(map);
?
Run Code Online (Sandbox Code Playgroud)