我在創建基於瀏覽器的遊戲(如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