本文介绍几个Dom操作的几个常用的案例。虽然现在各种web框架层出不穷,也很方便。但是了解最基本的实现方法对我们开发还是有很大的帮助的:
1.图片滚动案例
1.1 效果如下:
1.2 代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .wrap{ width:300px; height:335px; border:3px solid #b0b0b0; position: relative; overflow: hidden; margin:100px auto; } img{ position: absolute; top: 0; left:22px; } /*两个span一个在div的左一个在div的右*/ .wrap .left{ height:100%; width:150px; position: absolute; left:0; } .wrap .right{ height:100%; width:150px; position: absolute; right:0; } </style> </head> <body> <div class="wrap" id="box"> <img src="2.jpg" id="naruto"> <span class="left" id="pic_left"></span> <span class="right" id="pic_right"></span> </div> <script> var left = document.getElementById('pic_left'); var right = document.getElementById('pic_right'); var img = document.getElementById('naruto'); var count = 0; var time = null; //鼠标移入的时候动作 left.onmouseover = function () { time = setInterval(function () { count -= 2; count >= -100 ? img.style.left = count + 'px':clearInterval(time); },30) }; right.onmouseover = function () { time = setInterval(function () { count += 2; count < 0 ? img.style.left = count + 'px':clearInterval(time); },30) } </script> </body> </html>