我需要创建一个网站,该网站的项目具有无限的元素。我想使用海绵宝宝的元素,以及每秒有2个人死亡,4个人出生的事实。
因此,我将背景设置为比基尼泳裤的底部,每秒钟我要弹出4个字符,消失2个字符,没有结束且随机。那有什么办法可以在JAVASCRIPT上做到这一点吗?如果是这样,如何设置该代码?
谢谢。
我认为,实现这样的目标有多种方法,这是我会做的。
function deleteImage() {
const imagesAlreadyOnScreen = document.getElementsByClassName("images"); // give all your images a class so you can get them here.
//to delete a random image you would need a random number between 0 (included) and the amount of all images.
const indexToRemove = Math.floor(Math.random() * imagesAlreadyOnScreen.length);
//or use anther method to remove this element
imagesAlreadyOnScreen[indexToRemove].remove();
}
const parentElement = document.getElementById("parentElement"); // get the container where you want to put your images in.
function addImage() {
//create img element
const img = document.createElement("img");
//set all your attributes like width, height, ... here with img.setAttribute(attribute, value);
img.setAttribute('src', 'imageLink'); //here imageLink is the location of your image.
parentElement.appendChild(img) // add the image to the container
}
//use window.setInterval to execute these functions after a certain amount of time is reached.
window.setInterval(deleteImage, 500); // the second argument is in milliseconds, remove one image every half a second
window.setInterval(addImage, 250);
这是我的方法,请阅读一些教程等等,以便对JS有基本的了解,祝您好运!我认为w3schools是一个不错的起点。 https://www.w3schools.com/js/default.asp
还请注意,代码应放在try catch块中,但这不在问题的范围内。