一直覺得Agent是用來做網站導航和協助的不錯選擇,可惜MS Agent只有IE支援,而且好像載入速度不是很快,分析了一下覺得用Javascript絕對可以做到,以前對Javascript都是抄來抄去,趁此機會也徹底學一學。OK,Let's Begin
Javascript既然是基於對象的語言,那麼大體上我們也可以按照OO的思路來設計自己的Agent
我們希望用戶端簡單調用一下就OK了,應當是如下的形式。
<script src="agent.js"></script>
<script language="JavaScript">
<!--
var agent = new Agent();
agent.run();
//-->
</script>
那麼首先我們就來建立一個agent.js,js建立一個對象很簡單只需要提供一個建構函式就OK了
function Agent()
{
this.imgAgent = "images/agent.gif";
}
那麼,接下來的任務就是讓這個對象擁有一個run方法,這個方法應當僅僅就是輸出最後拼湊好的html,我們先簡單實現一下。
Agent.prototype.run=function()
{
var agentHtml = "<img src="+this.imgAgent;
agentHtml += " id=\"agent1\"";
agentHtml += " style=\"position:absolute;left:50;top:50;cursor:move\"";
agentHtml += " onselectstart=\"return false\"";
agentHtml += " onmousedown=\"mousedown(this)\"";
agentHtml += " onmouseup=\"mouseup()\"";
agentHtml += " onmousemove=\"mousemove()\"";
agentHtml += ">";
return document.write(agentHtml);
}
從上面代碼可以看出,我們實現的第一個精靈效果就是可以拖動精靈到介面任意一個地方,只需實現一下onmousedown,onmousemove,onmousemove三個事件即可
var currentMoveObj = null; //當前拖動對象
this.setImage=function(img)
{
imgAgent = img;
}
function dblclick(obj)
{
obj.src= "images/chaosai.gif";
}
function mousedown(obj)
{
currentMoveObj = obj; //當對象被按下時,記錄該對象
//查了一下資料setCapture的意思是:
//捕捉觸發事件時的焦點對象並使滑鼠焦點始終綁定該對象。
//很關鍵不然靈敏度會很低
currentMoveObj.setCapture()
relLeft = event.x - currentMoveObj.style.pixelLeft;
relTop = event.y - currentMoveObj.style.pixelTop;
}
function mouseup()
{
if(currentMoveObj!=null)
{
currentMoveObj.releaseCapture();
currentMoveObj=null;
}
}
function mousemove()
{
if(currentMoveObj != null)
{
currentMoveObj.style.pixelLeft=event.x-relLeft;
currentMoveObj.style.pixelTop=event.y-relTop;
}
}