javascript - 如何将一些 css 属性添加到已有的属性中?

标签 javascript css

我正在尝试优化我的 JavaScript 代码,但我陷入困境。

我有两组 CSS 属性,并且分别有两个 JavaScript 函数来发挥它们应有的作用 - 请查看此演示:

https://codepen.io/anon/pen/xNbdvr

每个组代表 body 元素的不同属性。

在这种情况下没关系,但我正在尝试找出一个通用函数 - 我有这样的东西:

function universal(color) {
  const selectedColor = color.value;
  const selectedProperty = color.name;
  const testSelection = document.querySelectorAll(`[name=${selectedProperty}`);

  for (let i = 0; i < testSelection.length; i++) {
    if (testSelection[i].checked) {
      document.body.style.cssText = `${selectedProperty}: ${selectedColor};`;
    }
  }
}
<p>Background Color</p>
<input type="radio" id="red" value="red" name="background-color" onclick="universal(this)" checked/>
<label for="red">red</label><br>
<input type="radio" id="green" value="green" name="background-color" onclick="universal(this)" />
<label for="green">green</label>

<p>Color</p>
<input type="radio" id="blue" value="blue" name="color" onclick="universal(this)" checked/>
<label for="blue">blue</label><br>
<input type="radio" id="orange" value="orange" name="color" onclick="universal(this)" />
<label for="orange">orange</label>

https://codepen.io/anon/pen/xNbdJg

问题是它覆盖了我的 CSS 属性而不是添加它们。我知道 .style.cssText 的工作原理是这样的,所以我需要不同的解决方案来解决这个问题。

理想的解决方案是这样的情况:

  • selectedProperty我有颜色/背景颜色(取决于我点击的组)

  • 这样的代码将是完美的:document.body.style.selectedProperty = selectedColor;

但我当然不能这么做。

您知道在这种情况下使用变量下存储的值的方法吗?

我希望我想要实现的目标是可以理解的。

最佳答案

您可以使用它来编辑正文的 CSS 属性,同时保留现有属性:

document.body.style[selectedProperty] = selectedColor

完整示例如下:

function universal(color) {
  const selectedColor = color.value;
  const selectedProperty = color.name;
  const testSelection = document.querySelectorAll(`[name=${selectedProperty}`);

  for (let i = 0; i < testSelection.length; i++) {
    if (testSelection[i].checked) {
      document.body.style[selectedProperty] = selectedColor;
    }
  }
}
<p>Background Color</p>
<input type="radio" id="red" value="red" name="background-color" onclick="universal(this)" checked/>
<label for="red">red</label><br>
<input type="radio" id="green" value="green" name="background-color" onclick="universal(this)" />
<label for="green">green</label>

<p>Color</p>
<input type="radio" id="blue" value="blue" name="color" onclick="universal(this)" checked/>
<label for="blue">blue</label><br>
<input type="radio" id="orange" value="orange" name="color" onclick="universal(this)" />
<label for="orange">orange</label>

关于javascript - 如何将一些 css 属性添加到已有的属性中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009940/

相关文章:

html - 引导覆盖

javascript - highcharts 零值导致图表中途而不是底部

html - 为什么我的最后一个跨度打破了我的 :after styling?

javascript - 如何将图像数组插入到 swipebox 画廊中?

javascript - Mapbox Geolocation,如何加载到 map 中?

javascript - 在 Mapbox 标记弹出窗口中显示 Highchart 折线图

javascript - 如何使用不同的 JSHint 选项检查两组文件? (grunt.js)

html - 未应用文档头中的 css 样式

css - 为什么@font-face 不起作用?

javascript - 显示 :none 时在输入字段中切换