【问题标题】:How to edit a style of a div from a button with if? [duplicate]如何使用if从按钮编辑div的样式? [复制]
【发布时间】:2019-02-17 18:29:25
【问题描述】:

我想让绿色的变成蓝色和绿色,把 Hi 变成 Hello。有人可以用简单的 html 方式告诉我如何使用按钮编辑样式和文字。

function functionl {
  alert('success')
}
.L1 {
  padding: 0px;
  border: 1px;
  border-radius: 200% 0px 200% 0px;
  border-color: green;
  background-color: green;
  font-size: 50px;
  color: white;
  width: 50%;
  height: 47%;
}

.L2 {
  padding: 0px;
  border: 1px;
  border-radius: 0px 200% 0px 200%;
  border-color: green;
  background-color: green;
  font-size: 50px;
  color: white;
  width: 50%;
  height: 47%;
}

.button1 {
  height=5%;
  font-size: 35;
  background-color: Red;
  color: blue;
  border-radius: 30px 30px 30px 30px;
}
<button class="L2">Hi</button><button class="L1">Hi</button><br>
<button class="L1">Hi</button><button class="L2">Hi</button>
<center><button class="button1" onclick="functionl()">Click me</button></center>

我希望有人向我展示如何编辑我的代码以及如何通过按钮编辑任何样式

【问题讨论】:

  • 我知道 js,但问题是它似乎不起作用:我尝试了 "document.getElementById('L1').style[background-color]=red" 并且它仍然不想工作我什至尝试将其附加到函数
  • 您的答案在我发布的第二个链接中。如错误所示,您在 JavaScript 中打错了字;在function1 之后应该有一个((之后应该有一个))。
  • 你能像 document.getElement.... 那样写吗?
  • 谢谢我正在尝试

标签: html css


【解决方案1】:

我相信这就是您正在寻找的:

function functionl() {
  for (let e of document.querySelectorAll('.L1, .L2')) {
    if (e.innerText == 'Hi') {
      e.style.backgroundColor = 'blue';
      e.innerText = 'Hello';
    } else {
      e.style.backgroundColor = 'green';
      e.innerText = 'Hi';
    }
  }
}
.L1 {
  padding: 0px;
  border: 1px;
  border-radius: 200% 0px 200% 0px;
  border-color: green;
  background-color: green;
  font-size: 50px;
  color: white;
  width: 50%;
  height: 47%;
}

.L2 {
  padding: 0px;
  border: 1px;
  border-radius: 0px 200% 0px 200%;
  border-color: blue;
  background-color: blue;
  font-size: 50px;
  color: white;
  width: 50%;
  height: 47%;
}

.button1 {
  height=5%;
  font-size: 35;
  background-color: Red;
  color: blue;
  border-radius: 30px 30px 30px 30px;
}
<body>
  <button class="L2">Hello</button><button class="L1">Hi</button><br>
  <button class="L1">Hi</button><button class="L2">Hello</button>
  <center><button class="button1" onclick="functionl()">Click me</button></center>
</body>

【讨论】:

  • 我只是稍微整理一下您的代码,如果可以的话。目前效率很低。
  • 去吧,我还没喝咖啡;p
  • @wizzwizz4 谢谢。
  • @Miroslav 谢谢
  • @wizzwizz4 是的,没关系。 IE11 甚至不想支持 IE11 所以没有伤害没有犯规:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2022-07-25
  • 1970-01-01
相关资源
最近更新 更多