我想使用“鼠标拖动”来拖动框内背景的位置。
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;
}
HTML:
<div id = "map" src = "WorldMap.png" onmousedown = "MouseMove(this)"> </div>
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";
}
什么也没发生,没有错误,没有警告,什么都没有...我尝试了很多东西:div内绝对定位的图像(你可以猜到为什么这不起作用),div内的可拖动div,带有背景图像,带有拖放功能的表格,最后我尝试了这个:
function MouseMove () {
e.style.backgroundPositionX = 10 + 'px';
e.style.backgroundPositionY = 10 + 'px';
e.style.cursor = "move";
}
这可行,但它与鼠标的位置无关,pageX
和 pageY
也不起作用。
现场演示:http://jsfiddle.net/VRvUB/224/
P.S:无论您的想法是什么,请不要用 JQuery 编写
最佳答案
根据您的问题,我了解到您需要帮助来实现实际的“拖动”行为。我猜不会。不管怎样,这是我努力的结果:http://jsfiddle.net/joplomacedo/VRvUB/236/
拖动仅在鼠标按钮时发生,并且......好吧,它的行为正如我认为您可能想要的那样。如果你还没有,就看看 fiddle =)
这里是代码,供那些想在这里查看的人使用:
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);
关于javascript - 使用鼠标拖动来控制背景位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13367959/