js常用坐标(一)

offset

1.offsetWidth:获取当前对象的宽度(width+padding+border);
2.offsetHeight:获取当前对象的高度(height+padding+border);
3.offsetLeft:获取当前对象到其上层左边的距离;
4.offsetTop:获取当前对象到其上层顶部的距离;

  注意: offset是可读属性,用来获取对象的可见宽高及位置.
  offset与style属性的区别是:
    1.style属性返回值带有单位
    2.style属性可以设置百分比
    3.style属性没有设置,返回空字符串,offset可以获取

实例

碰撞检测

css样式
.wrap{
    width: 500px;
    height: 300px;
    border: 1px solid red;
    position: relative;
}
#div1{
    position: absolute;
    width: 50px;
    height: 50px;
    background-color: red;
    border-radius: 25px;
}

js样式

var wrapDiv = document.querySelector(".wrap");
var div1 = document.getElementById("div1");
var x = wrapDiv.clientWidth- div1.offsetWidth;
var y= wrapDiv.clientHeight - div1.offsetHeight;
var speedx = 1;
var speedy = 1;
timer = setInterval(function(){
    if(div1.offsetLeft >=x){
    speedx *=-1;        
    }
    else if(div1.offsetLeft<0){
    speedx *=-1; 
    }
    div1.style.left = div1.offsetLeft + speedx + "px";
    div1.style.top = div1.offsetTop + speedy + "px";
},10);

你可能感兴趣的:(js常用坐标(一))