简体   繁体   中英

display images from an array with different position (javascript)

<body onLoad="init()">
    <div id="list">

        <script>
            function init() {
                var items = [
                    {id:'cp',image:'images/lvlOne/cellphone.png',style:'position:absolute;top:20px;left:290px'},
                    {id:'nl',image:'images/lvlOne/necklace.png'},
                    {id:'teddy_bear',image:'images/lvlOne/teddy_bear.png'},
                    {id:'choco',image:'images/lvlOne/chocolate.png'}
                ];

                var list = document.getElementsByTagName('div');

                for(i = 0; i < 3; i++) {
                    var item = items(Math.floor(Math.random() * items.length), 1)[0];

                    var image = document.createElement('img');
                    image.src = item.image;

                    list.appendChild(image);
                }
            }
        </script>
    </div>
</body>

I can retrieve random images but I cannot specify their position.

They randomize but I cannot change their position. I tried inline css but unfortunately it doesnt work for me.

Well I do not see you setting the style

if (item.style) {
    image.setAttribute("style", item.style);
}

The way you are loading the item also looks incorrect, try:

var random_item_key = Math.floor(Math.random() * items.length),
    item = items[ random_item_key ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM