2011-03-10 75 views
0

所以我有這個腳本來移動圖像。但我想這樣做,所以我不能將圖像的底部移動到底部60像素以上。在javascript中將圖像的位置限制在可視區域?

function right(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; // get just the number and not the units 
    document.getElementById(id).style.left = current - 5 + 'px'; // taking advantage of JavaScript's strange but sometimes useful type conversion. The subtraction converts it to an int and the addition converts it back to a string. 
    document.getElementById(id).src = 'guyr.png' 
} 

function left(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    document.getElementById(id).style.left = parseInt(current) + 5 + 'px'; // here we can't use that trick 
} 

function up(id) { 
    document.getElementById(id).style.top.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    document.getElementById(id).style.top = current - 5 + 'px'; 
} 

function down(id) { 
    document.getElementById(id).style.top.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    document.getElementById(id).style.top = parseInt(current) + 5 + 'px'; 
} 

回答

0

首先,你必須檢測瀏覽器的高度:

var myHeight; 
if(typeof(window.innerHeight) == 'number') { 
    //Non-IE  
    myHeight = window.innerHeight; 
} else if(document.documentElement && (document.documentElement.clientHeight)) { 
    //IE 6+ in 'standards compliant mode' 
    myHeight = document.documentElement.clientHeight; 
} else if(document.body && (document.body.clientHeight)) { 
    //IE 4 compatible 
    myHeight = document.body.clientHeight; 
} 

然後,您可以設置條件:

if(current > myHeight - 60) { 
    // do your function 
} 
+0

不,我想讓這個對象是移動距離底部不能超過60像素。 – 2011-03-10 03:13:57

+0

糾正了病情,爲你工作? – Raptor 2011-03-10 03:16:53

+0

爲回到IE4提供支持的榮譽。 – sdleihssirhc 2011-03-10 03:18:12

相關問題