
网页看到非常常见的一个图片切换效果:在淘宝、JD等购物时,介绍产品的图片会有多张,一般是显示一张,底下有一排小图片,鼠标放到小图片上大图片会切换.参考vivo X5M 移动4G手机 .下面记录一下实现的过程.
1. getElementById()
该方法是操作dom非常常用的一个方法,比如有一p标签,id设为pid,通过getElementById(“pid”)就可以对该元素进行操作.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>demo</title><script type="text/javascript">function changeText(){document.getElementById("pid").innerHTML="It works!";}</script></head><body><p id="pid" onmouseover="changeText()">Hello word!</p></body></html>上面代码中在body中写了一个p标签,id为pid,当鼠标放到p标签上方的时候触发onmouseover事件,执行changeText()方法,将p标签内的文档改变.<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>demo</title><script type="text/javascript">function changeUrl(){var baiduurl=document.getElementById("aid");baiduurl.getAttribute("href");baiduurl.setAttribute("href", "http://www.taobao.com");baiduurl.innerHTML="淘宝";}</script></head><body><a href="http://www.baidu.com" id="aid" onmouseover="changeUrl()">百度首页</a></body></html>上面代码中,body中有一个a标签,通过getElementById()获取a标签,baiduurl.getAttribute(“href”)的值为默认的href属性,通过baiduurl.setAttribute(“href”, “http://www.taobao.com“)设置以后,该属性值改变.完整代码:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>on</title><style type="text/css" media="screen">*{ padding: 0;}body{ font-family: 微软雅黑;}#imgbox{width: 320px;height: 490px;padding: 10px;box-shadow: 5px;border: 1px solid #ccc;border-radius: 10px;} #phoneimg{ padding: 10px; border-color: 1px solid #cccccc;}</style></head><body> <div id="imgbox"><img src="images/phone1.jpg" height="400" width="320" alt="phone" id="phoneimg"> <p id="decimg">phone image1</p> </div> <table><tbody><tr><td width="50px"><img src="images/phone2.jpg" height="100" width="80" title="phone image2" alt="" onmouseover="changeImg(this)" ></td><td width="50px"><img src="images/phone3.jpg" height="100" width="80" title="phone image3" alt=""onmouseover="changeImg(this)" ></td><td width="50px"><img src="images/phone4.jpg" height="100" width="80" title="phone image4" alt=""onmouseover="changeImg(this)" ></td><td width="50px"><img src="images/phone5.jpg" height="100" width="80" title="phone image5" alt=""onmouseover="changeImg(this)" ></td></tr></tbody> </table> <script type="text/javascript"> function changeImg(whichpic){var imgattr=whichpic.getAttribute("src"); var phoneimg=document.getElementById("phoneimg"); phoneimg.setAttribute("src",imgattr); var dectext=whichpic.getAttribute("title"); document.getElementById("decimg").innerHTML=dectext; } </script></body></html>下一步学习一下怎么实现局部放大,大家有什么好的方法吗?可以一起探讨。