Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - Cannot set width and height of cloned element

I cloned an image element using JS. I can move it around by setting the left and top attributes of the clone. However I cannot change the size.

var sprite_org = "WEs1";
var sprites = new Array(7);

var org = document.getElementById(sprite_org);
sprites[0] = org;

for (var i=1; i<7; i++) {
    let clone = org.cloneNode(true);
    clone.setAttribute( 'id', "Sprite" + i );
    org.parentNode.appendChild(clone);
    sprites[i] = document.getElementById("Sprite"+i);
    sprites[i].style.top = "0px";
    sprites[i].style.width = "500px";
}
question from:https://stackoverflow.com/questions/65852216/cannot-set-width-and-height-of-cloned-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try cleaning this up a bit.

for (var i=1; i<7; i++) {
    let clone = org.cloneNode(true);
    clone.setAttribute( 'id', "Sprite" + i );
    clone.style.top = "0px";
    clone.style.width = "500px";
    sprites[i] = clone;
    org.parentNode.appendChild(clone);
}

Also images have width and height "attributes" not just the css styling of them:

clone.width = 500;
clone.height = 300;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...