设置函数图像样式

Style function image?

本文关键字:样式 图像 函数 设置      更新时间:2023-09-26

我目前有一个javascript函数的设置。如何使某些 css 样式应用于图像?

这是我的代码:

function iCall1() {
    var img = document.createElement('img');
    img.src = "i1.png";
    document.body.appendChild(img);
}

出于不同的原因,我不想将图像源放在我的 html 文档中。

通过添加类:

function iCall1() {
    var img = document.createElement('img');
    img.src = "http://placehold.it/400x150";
    img.className = "myClass";
    document.body.appendChild(img);
}
iCall1();
.myClass {
  border: 10px solid red;
}

或者通过添加 ID:

function iCall1() {
    var img = document.createElement('img');
    img.src = "http://placehold.it/400x150";
    img.setAttribute("id", "myID");
    document.body.appendChild(img);
}
iCall1();
#myID {
  border: 10px solid red;
}