js實(shí)現(xiàn)小球在頁(yè)面規(guī)定的區(qū)域運(yùn)動(dòng)
本文實(shí)例為大家分享了js控制小球在規(guī)定范圍運(yùn)動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下
小球在頁(yè)面規(guī)定的區(qū)域運(yùn)動(dòng),碰到邊界就改變運(yùn)動(dòng)方向。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>小球運(yùn)動(dòng)</title>
<style type="text/css">
#box {
width: 600px;
height: 300px;
border: 1px solid red;
position: relative;
}
#ball {
width: 50px;
height: 50px;
border-radius: 25px;
background-color: yellow;
position: absolute;
top: 0;
left: 0;
}
button {
position: relative;
}
</style>
</head>
<body>
<div id="box">
<div id="ball">
</div>
</div>
<button id="stop" onclick="fly()">開始</button>
<button id="stop" onclick="stop()">停止</button>
<script type="text/javascript">
var ball = document.getElementById("ball");
//console.log(ball.offsetLeft);
var sport;
function fly() {
var speedx = 1;
var speedy = 1;
sport = setInterval(function () {
ball.style.left = ball.offsetLeft + speedx + 'px';
ball.style.top = ball.offsetTop + speedy + 'px';
if (ball.offsetTop >= 300 -50 || ball.offsetTop <= 0) {
speedy *= -1;
}
if (ball.offsetLeft >= 600 -50 || ball.offsetLeft <= 0) {
speedx *= -1;
}
}, 10)
}
function stop() {
clearInterval(sport); //停止小球的運(yùn)動(dòng)
}
</script>
</body>
</html>
效果圖:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- JavaScript+canvas實(shí)現(xiàn)框內(nèi)跳動(dòng)小球
- JavaScript結(jié)合Canvas繪畫畫運(yùn)動(dòng)小球
- JavaScript canvas實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)小球
- 原生js實(shí)現(xiàn)移動(dòng)小球(碰撞檢測(cè))
- 用js實(shí)現(xiàn)小球的自由移動(dòng)代碼
- js實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的小球
- JavaScript實(shí)現(xiàn)小球沿正弦曲線運(yùn)動(dòng)
- p5.js入門教程之小球動(dòng)畫示例代碼
- 原生js實(shí)現(xiàn)彈跳小球
- 原生js實(shí)現(xiàn)彈動(dòng)小球效果
相關(guān)文章
詳解JavaScript中Math內(nèi)置對(duì)象基本方法的使用
Math?是javaScript的內(nèi)置對(duì)象,包含了部分?jǐn)?shù)學(xué)常數(shù)屬性和數(shù)學(xué)函數(shù)方法。本文將詳細(xì)講解Math基本方法的使用,感興趣的小伙伴可以學(xué)習(xí)一下2022-04-04
js 判斷一組日期是否是連續(xù)的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇js 判斷一組日期是否是連續(xù)的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2016-07-07
網(wǎng)頁(yè)自動(dòng)跳轉(zhuǎn)代碼收集
網(wǎng)頁(yè)自動(dòng)跳轉(zhuǎn)代碼收集2009-09-09
使用原生js實(shí)現(xiàn)頁(yè)面蒙灰(mask)效果示例代碼
像js的框架Extjs的mask()和unmask()功能提供了蒙灰效果,當(dāng)然jquery也提供了這種蒙灰方法,下面有個(gè)示例,大家可以參考下2014-06-06
JS Pro-深入面向?qū)ο蟮某绦蛟O(shè)計(jì)之繼承的詳解
一般的面向?qū)ο蟪绦蛘Z(yǔ)言,有兩種繼承方法——接口繼承(interface inheritance)和實(shí)現(xiàn)繼承(implementation inheritance)。接口繼承只繼承方法簽名,而實(shí)現(xiàn)繼承則繼承實(shí)際的方法。在JavaScript中,函數(shù)沒有簽名,所以在JavaScript只支持實(shí)現(xiàn)繼承,而且主要是依靠原型鏈(prototype chaining)來(lái)是實(shí)現(xiàn)的2013-05-05
javascript中的window.location.search方法簡(jiǎn)介
window.location.search方法是截取當(dāng)前url中“?”后面的字符串,示例如下,感興趣的朋友可以參考下2013-09-09

