SoFunction
Updated on 2025-02-28

Pure JS to implement background image switching effect code

html code
Copy the codeThe code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml">
<head>
<title>Background Switch</title>
<link href="css/" type="text/css" rel="Stylesheet" />
</head>
<body>
<div><ul><li></li><li></li><li></li><li></li></ul></div>
<!-- <div>1</div><div>2</div><div>3</div><div>4</div>-->
</body>
<script src="js/" type="text/javascript" ></script>
</html>

Because the javascript logical order is relatively strong, we need to consider the location of reference js
css code
Copy the codeThe code is as follows:

body {font-size:12px;}
div{ width:950px; height:800px; margin:0 auto; border:solid 1px #d0d0d0;}
li{ list-style-type:none;border:solid 1px #d0d0d0; float:left; margin: 1px; padding:0 5px; height:12px; width:10px;}
/*div{ width:6px; height:14px; margin:1px; padding:0 5px; float:left; border:solid 1px #d0d0d0;}*/

JavaScript code part:
Copy the codeThe code is as follows:

=init;
var element= ("li");
function init() //Initialize background color
{
var element= ("li");
for(var i=0; i<4;i++)
{
var k=i+1;
element[i].="url(images/"+()+".jpg)";
}
}
function addclick()
{
for(var i=0; i<4;i++)
{
var k=i+1;
if()
element[i].attachEvent("onclick", new Function("bgchage("+k+");")); //Create events cannot be directly .onclick but need to use .attachEvent("event", new Function("Calling function("+parameter+");"));IE6 pass
else
element[i].addEventListener("click", new Function("bgchage("+k+");"),false);
}
}
function bgchage(t) //Change background color according to color block
{
("body")[0].="url(images/"+t+".jpg)";
}
addclick();

The js part should pay attention to the compatibility of writing events, and in fact, the idea of ​​jq is to write many functions into plug-ins for your own use. If you write in JavaScript, you can write your own class library for repeated use, and you don’t have to bear the burden of the jquery class library. Actually, I am not saying that jquery is not good. From a broad perspective, the size of jquery's plug-in does not have much impact. I watched the video of the Baidu front-end exchange meeting on the front-end event and found that the other person's class library was also written by JS himself, which gave me the motivation to continue learning js.