JS实现图片切换
尝试使用JS实现点击按钮切换图片,可以通过添加或删除display属性来隐藏或显示图片,同时设置button属性来改变按钮的样式,实现图片切换的效果。

实现代码
下面是实现图片切换的HTML,JS和CSS代码:
<body>
<h1>JS实现图片的切换</h1>
<div class="container">
<div class="one">
<div class="one-left">
<button id="pre"><b><</b></button>
</div>
<div class="one-center">
<ul>
<li style="display:none" id="a"><img src="images/1.jpg" width="600" height="300"></li>
<li style="display:none" id="b"><img src="images/2.jpg" width="600" height="300"></li>
<li style="display:none" id="c"><img src="images/3.jpg" width="600" height="300"></li>
<li style="display:block" id="d"><img src="images/4.jpg" width="600" height="300"></li>
</ul>
</div>
<div class="one-right">
<button id="next"><b>></b></button>
</div>
</div>
</div>
</body>
<script language="javascript">
var a=document.getElementById("a");
var b=document.getElementById("b");
var c=document.getElementById("c");
var d=document.getElementById("d");
var b1=document.getElementById("pre");
var b2=document.getElementById("next");
var num=4;
b1.onclick=function(){
num--;
if(num<1)
num=4;
panduan();
}
b2.onclick=function(){
num++;
if(num>4)
num=1;
panduan();
}
function panduan(){
if(num==1){
a.style.display="block";
b.style.display="none";
c.style.display="none";
d.style.display="none";
}
if(num==2){
a.style.display="none";
b.style.display="block";
c.style.display="none";
d.style.display="none";
}
if(num==3){
a.style.display="none";
b.style.display="none";
c.style.display="block";
d.style.display="none";
}
if(num==4){
a.style.display="none";
b.style.display="none";
c.style.display="none";
d.style.display="block";
}
}
</script>
<style>
*{
margin:0;
padding:0;
}
h1{
text-align:center;
}
li{
list-style:none;
float:left;
}
.container{
width:1000px;
height:1000px;
margin:0 auto;
}
.one{
width:700px;
height:400px;
margin:100px auto;
}
.one-center{
width:600px;
height:300px;
float:left;
}
.one-left{
width:50px;
height:300px;
float:left;
}
.one-right{
width:50px;
height:300px;
float:right;
}
button{
width:50px;
height:300px;
background-color:#999;
border:none;
outline:none;
}
button:hover{
background-color:#666;
}
</style>
在实现过程中,主要要注意以下两个问题:
- 如何隐藏图片:利用style.display属性设置图片的display属性来控制图片的显示和隐藏。
- 按钮点击和样式:通过修改button的相关属性,来改变按钮的样式,在JS中添加click事件,实现按钮点击后图片切换的效果。
最终效果如图所示:

原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7282.html
