【问题标题】:Variable set to global does not style element设置为全局的变量不设置元素样式
【发布时间】:2020-12-16 08:49:33
【问题描述】:

我有以下代码:

let fireball; //global variable

fireball = document.createElement("img") //variable on local
fireballArray.push(someFunction(fireball, {
 src: "img.png", width: "38" }))

fireball.style.display = "none" //global variable

我的目标是 fireball = document.createElement("img") 可以设置样式(在本例中为隐藏)

但是,document.createElement("img") 不会隐藏。有什么帮助吗?谢谢

警告:fireball = document.createElement("img") 此变量必须保留在本地范围和 style.display: none 必须在另一个范围内(如代码所示)

【问题讨论】:

  • 因为你在本地调用了这个:document.createElement("img"),我认为它不能被样式化(只能在同一范围内)我认为
  • 您是否尝试将其设为fireball.setAttribute("style", "display:none;");
  • 好吧,其实我想在用户点击按钮时不显示(所以之后必须不显示)

标签: javascript html css dom styles


【解决方案1】:

当你创建你的 img 时:

function myFunction() {
  var fireball = document.createElement("img");
  fireball.setAttribute("src", "img_pulpit.jpg");
  fireball.setAttribute("width", "304");
  fireball.setAttribute("height", "228");
  fireball.setAttribute("alt", "The Pulpit Rock");
  fireball.setAttribute("id", "UniqId"); // It is important to set an uniq ID
  document.body.appendChild(fireball);
}

然后应用集合,通过 Id getElementById 获取元素:

function myFunction2() {
  var fireball = document.getElementById("UniqId");
  fireball.setAttribute("style", "display:none; border:3px solid red;");
  document.body.appendChild(fireball);
}

你可以试试 w3C 演示:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_create

【讨论】:

  • 调用的时候可以直接设置样式。 var fireball = document.createElement("img"); fireball.setAttribute("style", "border: 3px solid red"); document.body.appendChild(fireball );
  • 是的,但我想在之后设置样式
  • 你真的不需要那个。如果你不想要,你可以删除它。它只是为了应用它。特别是通过 Id 将其应用于 get 元素是没有意义的,因为只有 1
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多