<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;/*绝对定位*/
left: 0px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var box1=document.getElementById("box1");
var btn1=document.getElementById("btn1");
var btn2=document.getElementById("btn2");
btn1.onclick=function(){
/*clearInterval(timer);
//alert(oldvalue)
timer=setInterval(function(){
//获取box1原来的left的值
var oldvalue=parseInt(getStyle(box1,"left"));
//在旧值上基础上增加
var newValue=oldvalue+19;
//判断newValue是否大于800,如果没有该语句就会可能不在800那里停住
if (newValue>800) {
newValue=800;
}
//将新值设置给box1
box1.style.left=newValue+"px";
//判断
if (newValue===800) {
clearInterval(timer);
}
},30);*/
move(box1,800,10);
};
//点击按钮后box1向左移动
btn2.onclick=function(){
move(box1,0,-0);
};
};
//设置定时调用标识
var timer;
/*
* 参数
* obj:要执行的动画
* target:执行动画的目标位置
* speed:移动的速度(正向右边移动,负向左yid)
*/
function move (obj,target,speed) {
//关闭点击开始之前的定时调用
clearInterval(timer);
//获取元素目前的位置
var current=parseInt(getStyle(obj,"left"));
//判断数度的正负
//从0-800,为正
//从800-0,为负
if(current>target){
speed=-speed;
}
//alert(oldvalue)
timer=setInterval(function(){
//box1原来的left的值
var oldvalue=parseInt(getStyle(obj,"left"));
//在旧值上基础上增加
var newValue=oldvalue+speed;
//判断newValue是否大于800,如果没有该语句就会可能不在800那里停住
//向左移动需要判断newValue是否小于target
if ((speed<0&&newValue<target) || (speed>0&&newValue>target)) {
newValue=target;
}
//将新值设置给box1
obj.style.left=newValue+"px";
//判断
if (newValue===target) {
clearInterval(timer);
}
},30);
}
//查看元素的样式
function getStyle (obj,name) {
if (window.getComputedStyle) {
//支持所有浏览器
return getComputedStyle(obj,null)[name];
}else{
//只支持IE8
return obj.currentStyle[name];
}
}
</script>
</head>
<body>
<button id="btn1">点击按钮后box1向又移动</button>
<button id="btn2">点击按钮后box1向左移动</button>
<br /><br />
<div id="box1"></div>
<div style="width: 0;height: 1000px;border-left: 1px black solid;position: absolute;left: 800px;"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定时切换图片</title>
<script type="text/javascript">
window.onload=function(){
//获取img标签
var img1=document.getElementById("img1");
//创建数组存储图片
var imgArr=["1.jpeg","2.jpeg","3.jpeg","4.jpeg","5.jpeg"];
//创建变量保存索引
var index=0;
var btn1=document.getElementById("btn1");
//定义一个变量,用来保存定时器标识
var timer;
btn1.onclick=function(){
/*
* 开启定时器,来自动切换图片
*/
//开启时关闭当时定时器
clearInterval(timer);
timer=setInterval(function(){
img1.src=imgArr[index];
index++;
if (index>=imgArr.length) {
index=0;
}
},1000);
};
var btn2=document.getElementById("btn2");
btn2.onclick=function(){
clearInterval(timer);
};
};
</script>
</head>
<body>
<img id="img1" src="1.jpeg"/>
<br />
<br />
<button id="btn1">开始</button>
<button id="btn2">停止</button>
</body>
</html>