使用 javascript 更改 Bootstrap 颜色

问题描述 投票:0回答:1

我想使用 JavaScript 更改一些引导变量值。我知道我可以使用 SCSS,但我现在的要求是它需要在单击时发生,所以我认为 JavaScript 是最佳选择。

这就是我现在所拥有的。但这不起作用。控制台消息似乎书写正确,但 UI 颜色没有改变。

<button type="button" class="btn btn-primary" onclick="UpdateColor()">CHANGE COLOR ON CLICK</button>
<h3 class="text-primary">WHEN BUTTON IS CLICKED MY COLOR SHOULD CHANGE</h3>

<script>
    function UpdateColor() {
        var root = document.querySelector(':root');
        var rs = getComputedStyle(root);

        console.log('before', rs.getPropertyValue('--primary'));
        root.style.setProperty('--primary', 'red');
        console.log('after', rs.getPropertyValue('--primary'));
    }
</script>
javascript bootstrap-4
1个回答
0
投票

您似乎没有使用 CSS 变量...

添加“风格”标签:

<style>
  .text-primary {
    color: var(--primary);
  }
</style>

结果:

<button type="button" class="btn btn-primary" onclick="UpdateColor()">CHANGE COLOR ON CLICK</button>
<h3 class="text-primary">WHEN BUTTON IS CLICKED MY COLOR SHOULD CHANGE</h3>
<style>
  .text-primary {
    color: var(--primary);
  }
</style>
<script>
  function UpdateColor() {
    var root = document.querySelector(':root');
    var rs = getComputedStyle(root);

    console.log('before', rs.getPropertyValue('--primary'));
    root.style.setProperty('--primary', 'red');
    console.log('after', rs.getPropertyValue('--primary'));
  }
</script>

© www.soinside.com 2019 - 2024. All rights reserved.