简体   繁体   中英

Changing the Location of an Image added in Javascript with a CSS stylesheet

I'm still pretty new to HTML and the languages commonly associated with it. Right now, I'm trying to adjust the location of an image I added in through a function defined in Javascript like I usually would in CSS with something like margin-left: 100px .

EDIT: Added code and clarification

case 1:
        demo.innerHTML = "You win cookies!";
        var img = new Image();
        img.src = 'cookies.jpg';
        img.onclick = function() {
        window.location.href = 'http://link.com/';}

document.body.appendChild(img);

You can set properties to position elements via Javascript, eg:

var elem = document.getElementById("elementid"); elem.style.left=200; elem.style.top=200;

you may need to set:

elem.style.position='absolute';

 var img = new Image(); img.src = 'http://data.whicdn.com/images/27433830/large.jpg'; img.id = "myImage"; // <-- give it an ID img.onclick = function() { window.location.href = 'http://link.com/'; } document.body.appendChild(img); document.getElementById("button").onclick = function() { var image = document.getElementById("myImage"); image.src = "http://weknowyourdreamz.com/images/house/house-07.jpg"; }
 <button id="button">switch</button>

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