编程实现:节点操作应用,界面有一原图,要求如下:
1.点击“增加图片”按钮,随机增加一张图片,让其显示在已有图片的最后面。
2.点击“删除图片”按钮,删除最后一张图片,原图不能删。
3.点击“复制图片”按钮,复制原图,显示在已有图片的最后面。
4.点击“替换原图”按钮,将原图或复制的原图,全部替换成其他一张。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
img{
width: 300px;
height: 180px; //定义图片大小
}
</style>
</head>
<body>
<h1>喜欢的图片</h1>
<div>
<button onclick="fn1()">增加图片</button>
<button onclick="fn2()">删除图片</button>
<button onclick="fn3()">复制图片</button>
<button onclick="fn4()">替换原图</button>
</div>
<script>
var Div=document.createElement("div");
var im=document.createElement("img");
im.src="../img/imge1.jpeg";
im.setAttribute("name","1"); //为原图定义一个名字方便判断
Div.appendChild(im);
document.body.appendChild(Div);
var arr=["../img/imge2.jpeg","../img/imge3.jpeg","../img/imge4.jpeg","../img/例图1.png","../img/例图2.jpg"];
function fn1(){ //增加随机图片
var i=document.createElement("img");
i.src=arr[Math.round(Math.random()*4)]; //获取随机索引
Div.appendChild(i); //追加图片
}
function fn2(){ //删除图片
Div.children.length>1 ? Div.removeChild(Div.children[Div.children.length-1]):null; //如果子节点长度大于1,执行删除
}
function fn3(){ //复制图片
var aaa=im.cloneNode(true); //复制原图
Div.appendChild(aaa);
}
function fn4(){ //替换图片
//var i=document.createElement("img");
//i.src=arr[Math.round(Math.random()*4)];
//Div.replaceChild(i,Div.children[0]);
for(var i=0;i<Div.children.length;i++){
if(Div.children[i].getAttribute("name")==im.getAttribute("name"))
Div.children[i].setAttribute("src",arr[Math.round(Math.random()*4)]);
} //修改原图包括复制原图的地址以达到替换作用
}
</script>
</body>
</html>
如果对你有帮助的话,请点个赞,谢谢