我在创建基于浏览器的游戏(如Travian)的地图时遇到了一些麻烦。我创建了一个将地图拖入不同方向的函数,但每次单击不同的位置时,我都会直接改变位置,然后根据需要移动它。有没有解决这个问题的方法? JQuery需要吗? (我不是在使用Javascript这么好,所以我的代码可能比周围的代码最简单的方式是什么样子有点不同)基于浏览器的游戏的地图
全文档:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map</title>
<script type="text/javascript">
//object of the element to be moved
_item = null;
//stores x & y co-ordinates of the mouse pointer
mouse_x = 0;
mouse_y = 0;
// stores top,left values (edge) of the element
mapdiv_x = 0;
mapdiv_y = 0;
//bind the functions
function move_init()
{
document.onmousemove = _move;
document.onmouseup = _stop;
}
//destroy the object when we are done
function _stop()
{
_item = null;
}
//main functions which is responsible for moving the element (div in our example)
function _move(e)
{
mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX;
mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY;
if(_item != null)
{
_item.style.backgroundPosition = "-" + (mouse_x - mapdiv_x) + "px -" + (mouse_y - mapdiv_y) + "px";
}
}
//will be called when use starts dragging an element
function _move_item(mapdiv)
{
//store the object of the element which needs to be moved
_item = mapdiv;
mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX;
mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY;
oldmapdivx = _item.style.backgroundPositionX;
oldmapdivy = _item.style.backgroundPositionY;
mapdiv_x = oldmapdivx - mouse_x;
mapdiv_y = oldmapdivy - mouse_y;
mapdivx2 = mouse_x - mapdiv_x;
mapdivy2 = mouse_y - mapdiv_y;
}
</script>
<style type="text/css">
#mapdiv {
background-image:url('images/map.png');
background-repeat:no-repeat;
background-color:#666;
width:750px;
height:500px;
cursor: move;
}
</style>
</head>
<body onload="move_init()">
<div id="mapdiv" onmousedown="_move_item(this);"></div>
</body>
</html>
你从来不需要JQuery,它是用JavaScript编写的,所以你总是可以重新创建它给你的东西。但是,为什么你想要,因为它使生活变得如此简单;你可能想要JQuery。这是一个很好的工具,如果你刚刚开始使用JS,它会为你节省大量的痛苦。 – acrosman 2012-01-04 19:19:13