开发者

Restricting the position of an image to the viewable area in javascript?

So I have this script to move around an image. But I want to make it so I cant move the bottom of the image above the bottom 60 pixels.

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';
}


First, you have to detect the height of browser:

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; 
} 

Then, you can set condition :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜