国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

原生js實(shí)現(xiàn)碰撞檢測(cè)

瀏覽:117日期:2024-05-18 18:48:14

本文實(shí)例為大家分享了js實(shí)現(xiàn)碰撞檢測(cè)的具體代碼,供大家參考,具體內(nèi)容如下

隨手寫了個(gè)簡(jiǎn)單的碰撞檢測(cè)的代碼。檢測(cè)box1和box2是否發(fā)生碰撞,若發(fā)生碰撞,box2顏色發(fā)生隨機(jī)改變,并反彈到隨機(jī)位置。

<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <style> .box1,.box2{ width: 100px; height: 100px; background-color: #f00; position:absolute; } .box2{ background-color: #00f; left: 200px; top: 200px; } </style></head><body> <div class='box1'></div> <div class='box2'></div></body><script> var box1=document.querySelector('.box1'); var box2=document.querySelector('.box2'); box1.addEventListener('mousedown',mouseHandler); function mouseHandler(e){ if(e.type==='mousedown'){ e.preventDefault(); document.elem=this; document.pointX= e.offsetX; document.pointY= e.offsetY; document.addEventListener('mousemove',mouseHandler); this.addEventListener('mouseup',mouseHandler); }else if(e.type==='mousemove'){ this.elem.style.left= e.x-this.pointX+'px'; this.elem.style.top= e.y-this.pointY+'px'; hitText(this.elem,box2); }else if(e.type==='mouseup'){ document.removeEventListener('mousemove',mouseHandler); this.removeEventListener('mouseup',mouseHandler); } } function hitText(elem1,elem2){ var rect1=elem1.getBoundingClientRect(); var rect2=elem2.getBoundingClientRect(); var ponit1={x:rect1.x,y:rect1.y}; var ponit4={x:rect1.x+rect1.width,y:rect1.y+rect1.height}; if( ponit4.x>rect2.x&&ponit1.x<(rect2.x+rect2.width)&&ponit4.y>rect2.y&&ponit1.y<(rect2.y+rect2.height)){ elem2.style.backgroundColor=randomColor(); elem2.style.left=Math.round(Math.random()*document.documentElement.clientWidth)+'px'; elem2.style.top=Math.round(Math.random()*document.documentElement.clientHeight)+'px'; } } function randomColor(){ var a=Math.round(Math.random()*255); var b=Math.round(Math.random()*255); var c=Math.round(Math.random()*255); var color='rgb('+ a+','+b+','+c+')'; return color; }</script></html>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 邛崃市| 南乐县| 光泽县| 获嘉县| 安宁市| 安陆市| 滨海县| 彭山县| 苏尼特右旗| 双辽市| 沧州市| 精河县| 阿拉尔市| 连云港市| 太保市| 德兴市| 东乡| 保靖县| 望城县| 正定县| 柘荣县| 山东| 陵川县| 九寨沟县| 兴义市| 常山县| 聊城市| 梁平县| 额敏县| 威信县| 裕民县| 江城| 利辛县| 平安县| 南投市| 阿尔山市| 昌吉市| 涟水县| 龙江县| 河西区| 平阴县|