我想写一个JavaScript碰撞效果,但是获取documentElement.clientWidth总报错,怎么解决?
<!DOCTYPEhtml><html><head><styletype='text/css'>#div1{height:80px;width:80px;backgrou...
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#div1{height:80px;width:80px;background:red;position:absolute;}
</style>
<script>
window.onload=function(){
var oBtn=document.getElementById("button");
oBtn.onclick=function(){
startMove();
}
}
var iSpeedX=6;
var iSpeedY=20;
function startMove(){
setInterval(function(){
var oDiv = document.getElementById("div1");
console.log(oDiv.documentElement);
var l=oDiv.offsetLeft+iSpeedX;
var h=oDiv.offsetHeight+iSpeedY;
if(l>oDiv.documentElement.clientWidth-oDiv.offsetWidth){
iSpeedX*=-0.8;
}
if(h>oDiv.documentElement.clientHeight-oDiv.offsetHeight){
iSpeedY*=-0.8;
}
},30);
}
</script>
</head>
<body>
<input type="button" id="button" value="点击"/>
<div id="div1"></div>
</body>
</html> 展开
<html>
<head>
<style type='text/css'>
#div1{height:80px;width:80px;background:red;position:absolute;}
</style>
<script>
window.onload=function(){
var oBtn=document.getElementById("button");
oBtn.onclick=function(){
startMove();
}
}
var iSpeedX=6;
var iSpeedY=20;
function startMove(){
setInterval(function(){
var oDiv = document.getElementById("div1");
console.log(oDiv.documentElement);
var l=oDiv.offsetLeft+iSpeedX;
var h=oDiv.offsetHeight+iSpeedY;
if(l>oDiv.documentElement.clientWidth-oDiv.offsetWidth){
iSpeedX*=-0.8;
}
if(h>oDiv.documentElement.clientHeight-oDiv.offsetHeight){
iSpeedY*=-0.8;
}
},30);
}
</script>
</head>
<body>
<input type="button" id="button" value="点击"/>
<div id="div1"></div>
</body>
</html> 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询