使用CSS样式表更改在Javascript中添加的图像的位置

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

本文关键字:添加 图像 位置 Javascript 样式 CSS 使用      更新时间:2023-09-26

我对HTML和通常与之相关的语言还很陌生。现在,我正试图通过Javascript中定义的函数来调整我添加的图像的位置,就像我通常在CSS中使用margin-left: 100px一样。

编辑:添加代码和澄清

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);

您可以通过Javascript设置属性来定位元素,例如:

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

您可能需要设置:

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>