网络编程 
首页 > 网络编程 > 浏览文章

JS实现静止元素自动移动示例

(编辑:jimmy 日期: 2025/5/15 浏览:3 次 )
一个元素是静止的,使它在屏幕上实现自动移动。

这是一个比较简单问题,在学习中遇到了,把它写了下来。
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
#sp1{
border: red solid ;
display: inline-block;
width: 30px;
height: 20px;
font-size: 20px;
text-align: center;
}
</style>
<script>
var timenum;
var mar=0;//控制移动量的变量
var flag = 0;//实现控制左右移动的一个变量
//实现向右移动的函数
function moveright(){
sp1.style.marginLeft=mar+"px";
mar=mar+5;
}
//实现向右移动的函数
function moveleft(){
sp1.style.marginLeft=mar+"px";
mar=mar-5;
}

function go() {
var sp1 =document.getElementById("sp1");
var btn1 = document.getElementById("start");
if(!btn1.disabled){
btn1.disabled = true;
document.getElementById("pause").disabled=false;
}
sp1.innerHTML=parseInt(sp1.innerHTML)+1;
timenum = window.setTimeout(go,10);
if(flag==1){
window.setTimeout(moveleft,10);
}
if(flag==0){
window.setTimeout(moveright,10);
}
if(mar>(window.outerWidth)){
flag=1;
}
if(mar<0){
flag=0;
}
}
function stop(){
document.getElementById("start").disabled = false;
document.getElementById("pause").disabled=true;
window.clearTimeout(timenum);
}
</script>
</head>
<body>
<button id="start" <button id="pause" disabled>暂停</button>
<br/>
<span id="sp1">0</span>
</body>
</html>
上一篇:javascript页面渲染速度测试脚本分享
下一篇:js 获取元素下面所有li的两种方法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap