This article describes the method of dynamically switching pictures by js. Share it for your reference. The specific implementation method is as follows:
The index.css file is as follows:
Copy the code as follows:* {
margin: 0px;padding: 0px;
}
body {
width: 632px;
/*background-color: blue;*/
margin: 0 auto;
}
#imgsCom {
background-color: yellow;
/*Relative positioning, in order to use absolute positioning in the lower layer, use the origin of this div as the origin*/
position: relative;
}
#ulnav{
list-style-type: none;
position: absolute;
/*Use imgsCom as the origin to absolutely locate to the lower right corner*/
bottom: 0px;
right: 0px;
}
#ulnav li{
list-style-type: none;
float: left;
background-color: black;
color: white;
margin-right: 5px;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
cursor: pointer;
}
Index.html is as follows:
Copy the code as follows: <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js,css dynamically switch pictures</title>
<link href="css/index.css" rel="stylesheet" />
<script type="text/javascript">
function gel(id) {
return document.getElementById(id);
}
function clearLiBg() {
var mylis = gel("ulnav").childNodes;
for (var i = 0; i < mylis.length; i++) {
if (mylis[i].nodeType == 1) {
mylis[i].style.backgroundColor = "black";
}
}
}
window.onload = function() {
//Specify an attribute for all three li
var lis = gel("ulnav").childNodes;
for (var i = 0; i < lis.length; i++) {
if (lis[i].nodeType == 1) {
lis[i].onclick = function () {
//Replace the picture
gel("myimg").setAttribute("src", "images/" + this.innerHTML + ".png");
//All LI colors restore
clearLiBg();
//Replace the color of the LI background label
this.style.backgroundColor = "silver";
};
}
}
};
</script>
</head>
<body>
<div id="imgsCom">
<img src="images/1.png" id="myimg" />
<ul id="ulnav">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.