简体   繁体   中英

Creating image elements then setting style attributes through javascript error

So I created an image tag but I also want to be able to set attributes for the image tag created through the javascript that I have below

function start()
        {
            imageTag = document.createElement("IMG"); //Creates image tag
            w = window.innerWidth //finds width of web page
            h = window.innerHeight //finds height of web page
            pic = document.getElementsByTagName("img"); //finds the tag name of "img"
            x = Math.floor(Math.random()*(w))+1; //finds a random width that can be used for x coordinate that fits within site
            y = Math.floor(Math.random()*(h))+1; //finds a random height that can be used for y coordinate that fits within site
            pic.style.left = x+"px"; //Sets the style attribute that will be in the image tag that was created earlier *ERROR*
            pic.style.top = y+"px"; //Sets the style attribute that will be in the image tag that was created earlier *ERROR*
            imageTag.setAttribute("src", "popo.jpg" ); //sets the image tags source
            document.body.appendChild(imageTag);
        }

I can't seem to figure out why the style attribute of left and top aren't added like the other picture source attribute in the image tag that was created. If I have an image tag already in the html, then it works but not when I create one in javascript so this makes no sense because I feel like it should work.

Sounds like you'd benefit by keeping a reference to the last created image so you can set the position properties easily.

For example

var prevImage;

function start() {
    if (prevImage) {
        var x = Math.floor(Math.random() * window.innerWidth) + 1,
            y = Math.floor(Math.random() * window.innerHeight) + 1;            

        prevImage.style.left = x + 'px';
        prevImage.style.top = y + 'px';
    }
    var img = document.createElement('img');
    img.src = 'popo.jpg';
    document.body.appendChild(img);
    prevImage = img;
}

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