var items = ['imgs/garbagebag.svg', //[0]
'imgs/straw.svg', // [1]
'imgs/utensil.svg', // [2]
'imgs/chipbag.svg', // [3]
'imgs/eggs.svg', // [4]
'imgs/glasscup.svg', //[5]
'imgs/ketchupbottle.svg', //[6]
'imgs/jamjar.svg', //[7]
'imgs/milkbottle.svg', //[8]
'imgs/popbottle.svg', //[9]
'imgs/eggshell.svg', //[10]
'imgs/apple.svg', //[11]
'imgs/banana.svg', //[12]
'imgs/teabag.svg', // [13]
'imgs/leave.svg', // [14]
'imgs/jug.svg', // [15]
'imgs/tetrapak.svg', // [16]
'imgs/container.svg', // [17]
'imgs/plasticbottle.svg', // [18]
'imgs/can.svg', //[19]
'imgs/newspaper.svg', //[20]
'imgs/cerealbox.svg', // [21]
'imgs/book.svg', // [22]
'imgs/cardboard.svg', // [23]
'imgs/bag.svg' // [24]
]
// This is the black hole on the wall
var hole = document.getElementById("hole");
// starts functioning after 5 seconds
var start = setInterval(shuffle,5000);
// displays an random items from array one by one
function shuffle(){
hole.addEventListener("click",function(){
console.log("items");
items[Math.floor(Math.random()*items.length)]
});
}
嗨,所以这是一个迷你游戏,教用户如何回收利用。在屏幕截图中,用户需要单击黑洞/孔才能在黑洞内一个接一个地显示随机项(我尝试附加它,但之前不知道要创建什么)。我对如何实现这一目标感到困惑。我所拥有的似乎还不够。我感谢解决方案和提示。感谢您阅读我的帖子。
UPDATE: So the codes Elliot provided is working. But for some reasons, newly created + randomized images have no pixels! I tried assigning new width and height + z-index with className in css but that is not doing anything either. I hope this is not a complicated problem to solve T.T
It might be worthwhile restructuring your code slightly. It looks like you are grouping your items.
var items = [{
image: "imgs/garbagebag.svg",
type: "paper"
}, {
image: "imgs/straw.svg",
type: "paper"
},
...]
This gives you a lot more flexibility in the meta data behind each item.
Then you need to add the events
var hole = document.getElementById("hole");
function showItem(item) {
var img = document.createElement("img");
img.setAttribute("src", item.image);
// store type as data attribute so we can access it later
img.setAttribute("data-type", item.type);
if (hole.childNodes[0]) {
hole.removeChild(hole.childNodes[0]);
}
hole.appendChild(img);
}
function showRandomItem() {
var item = items[Math.floor(Math.random()*items.length)];
showItem(item);
}
hole.addEventListener("click", function() {
showRandomItem();
});
Here is a working version of this code on JSFiddle
https://jsfiddle.net/nxc5zpen/
It looks like the issues you might be having are due to SVG scaling. Here is a working JSFiddle with SVGs.
https://jsfiddle.net/Lhot76gm/1/
And here is another version using background images for the hole.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句