JavaScript连载31-图片动态切换以及关闭图片案例

tech2024-12-20  3

一、图标切换

<style> #box{ width:1200px; margin:0 auto; } </style> </head> <body> <div id="box"> <img src="img/img_01.png" alt="" id="icon"> <p></p> <button id="prev">上一张</button> <button id="next">下一张</button> </div> <script> window.onload=function (ev) { //1.获取标签 var icon = document.getElementById("icon"); var prev = document.getElementById("prev"); var next = document.getElementById("next"); //2.点击 var currentIdex = 1;//当前的图片索引 var minIndex = 1,maxIndex=5; //点击操作触发图片轮番图 prev.onclick=function (ev1) { if(currentIdex==minIndex){ currentIdex=maxIndex+1; } currentIdex--; icon.setAttribute("src","img/img_0"+currentIdex+".png"); }; next.onclick=function (ev2) { if(currentIdex==maxIndex){ currentIdex=minIndex-1; } currentIdex++; icon.setAttribute("src","img/img_0"+currentIdex+".png"); }; } </script> </body>

点击那两个按钮可以做到轮番显示图片

二、关闭图片案例

<style> div{ position:relative;/*子绝父相*/ display:inline-block;/*很关键如果没有图片就不能重叠上去了*/ } .close{ position:absolute; top:2px; right:2px; cursor:pointer; } </style> </head> <body> <div> <img src="img/img_02.png" alt=""> <img class="close" src="img/close.png" alt=""> </div> <script> window.onload = function (ev) { //1.获取关闭标签 var close = document.getElementsByClassName("close"); console.log(close); //另一种方式:var close = document.querySelector("#close"); //2.监听点击 close.onclick = function () { this.parentNode.remove();//去掉图片 //或者如下:设置父元素的style样式 this.parentNode.style.display="none"; } } </script>

点击右上角的叉,图片会消失。

三、源码:

D31_iconSwitch.htmlD31_2_CloseImage.html地址:https://github.com/ruigege66/JavaScript/blob/master/D31_iconSwitch.htmlhttps://github.com/ruigege66/JavaScript/blob/master/D31_2_CloseImage.html博客园:https://www.cnblogs.com/ruigege0000/:https://blog.csdn.net/weixin_44630050?t=1欢迎关注微信公众号:傅里叶变换,个人账号,仅用于技术交流
最新回复(0)