javascript|特效
今天在玩 google earth 4.0b,發現 Print Screen 下來的圖片很大,如果直接放在網頁上,因為尺寸太大又不合適,又不想壓縮圖片的尺寸,於是乎就想到了這種方法,沒想到實現起來比預想的要容易。這段代碼還相容 firefox。
限定滾動的範圍,不會出現背景。
用到onmousemove事件,圖片即時隨滑鼠移動而移動。
運行代碼框
<!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=gb2312" /><title>無標題文檔</title><style type="text/css"><!--#pic {width:420px;height:300px;border: 3px solid #ccc;background-image: url(01.jpg);background-repeat: no-repeat;background-position: 0px 0px;cursor: move;}--></style><script type="text/javascript"><!--var p = new Array();var speed = 0.05; //速度var picWidth = 1280; // 大圖的寬高var picHeight = 971;var x,y // 滑鼠點下去時背景的座標var x_new,y_new //位移var haveclick = false;function getmouseposition(event){if(document.all){x = document.body.scrollLeft+event.clientX;y = document.body.scrollTop+event.clientY;}else{x = event.layerX;y = event.layerY;}haveclick = true;}function movestop(){haveclick = false;}function movestart(event){if(haveclick){if(document.getElementById('pic').style.backgroundPosition.length==0){document.getElementById('pic').style.backgroundPosition="0px 0px";}p = document.getElementById('pic').style.backgroundPosition.split(" ")if(document.all){x_new = document.body.scrollLeft+event.clientX;y_new = document.body.scrollTop+event.clientY;}else{ x_new = event.layerX;y_new = event.layerY;}x2 = (speed*(x_new-x)+parseInt(p[0])).toString(10); // 計算位移量y2 = (speed*(y_new-y)+parseInt(p[1])).toString(10);if (x2<-picWidth+420) x2=-picWidth+420;if (y2>0) y2=0;if (x2>0) x2=0;if (y2<-picHeight+300) y2=-picHeight+300;document.getElementById('pic').style.backgroundPosition=x2+"px "+y2+"px";}}--></script></head><body><div id="pic" onmousemove="movestart(event)" > </div></body></html>
[Ctrl+A 全部選擇 提示:你可先修改部分代碼,再按運行]