1.点击自动切换图片
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #img{ width: 400px; height: 270px; } </style></head><body> <img src="./images/one.jpg" alt="" id="img"> <br> <button id="btn" >开始</button> <button id="btn1">停止</button> <script> window.onload=function(){ //让图片自动切换 src属性改变 //定义一个timer var timer; //获取图片 var img=document.getElementById("img"); //创建数组保存图片路径(src) var arr=["images/one.jpg","images/two.jpg","images/three.jpg","images/four.jpg","images/five.jpg"] //创建一个变量保存当前索引 var index=0; //获取按钮 var btn=document.getElementById("btn") btn.onclick=function(){ //创建一个定时器 timer=setInterval(function(){ index++; index=index%arr.length; // if(index>=arr.length){ // index=0 // } img.src=arr[index] },1000) } //停止切换图片 var btn1=document.getElementById("btn1") btn1.onclick=function(){ //关闭定时器 clearInterval(timer) } } </script></body></html>
2.滚动事件
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box{ width: 200px; height: 200px; position: absolute; background-color: cornflowerblue; } </style></head><body> <div id="box"></div> <script> window.onload=function(){ var box=document.getElementById("box"); //给box绑定一个滚轮事件判断滚动了没 box.onmousewheel=function(event){ event=event||window.event; //获取滚轮滚动的方向event.wheelDelta 只看正负 正向上 负向下 // alert(event.wheelDelta); if(event.wheelDelta>0){ //向上滚变短 box.style.height=box.clientHeight-5+"px"; }else{ //向下滚变长 box.style.height=box.clientHeight+5+"px"; } } } </script></body></html>
3.拖拽
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box{ width: 200px; height: 200px; background-color: coral; position: absolute; } </style></head><body> <div id="box"></div> <script> window.onload=function(){ //获取box var box=document.getElementById("box"); //为box绑定一个onmousedown鼠标按下事件 box.onmousedown=function(){ //为document绑定一个onmousemove鼠标移动事件 document.onmousemove=function(event){ event=event ||window.event; var left=event.clientX; //获取当前移动后的位置 var top=event.clientY; //修改box位置 box.style.left=left+"px"; box.style.top=top+"px"; } } //为box绑定onmuoseup鼠标松开事件 box.onmouseup=function(){ //鼠标松开后 box不移动 故onmousemove事件不存在 document.onmousemove=null; } } </script></body></html>