轻松实现JavaScript图片切换

轻松实现JavaScript图片切换

网页看到非常常见的一个图片切换效果:在淘宝、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>Hello word!</p> </body> </html>

上面代码中在body中写了一个p标签,id为pid,当鼠标放到p标签上方的时候触发onmouseover事件,执行changeText()方法,将p标签内的文档改变.

2. setAttribute()和getAttribute()

getAttribute()方法用于获取某一属性的值,setAttribute()方法用于给某一属性赋值。

<!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="https://www.baidu.com">百度首页</a> </body> </html>

上面代码中,body中有一个a标签,通过getElementById()获取a标签,baiduurl.getAttribute(“href”)的值为默认的href属性,通过baiduurl.setAttribute(“href”, ““)设置以后,该属性值改变.完整代码:

<!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> <img src="https://www.jb51.net/images/phone1.jpg" alt="phone"> <p>phone image1</p> </div> <table> <tbody> <tr> <td> <img src="https://www.jb51.net/images/phone2.jpg" title="phone image2" alt="" ></td> <td> <img src="https://www.jb51.net/images/phone3.jpg" title="phone image3" alt=""onmouseover="changeImg(this)" ></td> <td> <img src="https://www.jb51.net/images/phone4.jpg" title="phone image4" alt=""onmouseover="changeImg(this)" ></td> <td> <img src="https://www.jb51.net/images/phone5.jpg" 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>

下一步学习一下怎么实现局部放大,大家有什么好的方法吗?可以一起探讨。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwjzp.html