js函数的调用


js函数的调用

在使用js的函数中我们有时会有同一个函数多次使用的需求,而一个一个的调用函数会十分的麻烦,这时候我们可以将多次使用的函数先进行封装,然后调用,会十分的简单快捷

const box=document.getElementById('box')
const box1=document.getElementById('box1')
function crash( obj1,obj2){
    if(obj1.offsetLeft+obj1.offsetWidth<obj2.offsetLeft
||obj1.offsetTop+obj1.offsetHeight<obj2.offsetTop
||obj1.offsetTop>obj2.offsetTop+obj2.offsetHeight
||obj1.offsetLeft>obj2.offsetLeft+obj2.offsetWidth)
{
    obj2.style.background='green'
}
else
{obj2.style.background='black'}


}
//将函数封装,谁用谁去调用(move)
function move(obj){
obj.onmousedown=function(event){
const chaX=event.clientX-obj.offsetLeft
const chaY=event.clientY-obj.offsetTop


document.onmousemove=function(event){
    obj.style.left=event.clientX-chaX+'px'
    obj.style.top=event.clientY-chaY+'px'
   crash(box,box1)//函数执行,调用碰撞检测封装函数到实际元素中


}
document.onmouseup=function(){
    document.onmousemove=null
}
}
}move(box1)
move(box)//函数执行,调用碰撞检测封装函数到实际元素中

函数封装可以大大地节省我们写代码的时间,也可以提升js的简洁.

相关