【问题标题】:How to change bootstrap icon's attributes using javascript如何使用 javascript 更改引导图标的属性
【发布时间】:2021-11-28 15:04:20
【问题描述】:

我需要-

  1. 在加载 DOM 内容时创建引导图标(心形)
  2. 点击图标时,心形图标填充为红色(这里我使用心形填充图标)
  3. 两个图标都大于原始

document.addEventListener('DOMContentLoaded', function () {
      var heart = document.createElement('i')
      heart.className = 'bi bi-heart'
      document.querySelector('#posts').append(heart)
      heart.onclick = function () {
        this.className = 'bi bi-heart-fill'
        this.setAttribute('fill', 'red')
      }
    } )
<head><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"></head>
<body><div id="posts"></div></body>

当我单击心脏时,它会填充黑色,而不是红色。我也不知道如何通过增加宽度和高度的值来使其更大。我看到了与此相关的其他问题,但没有一个能解决我的问题。

【问题讨论】:

    标签: javascript css bootstrap-icons


    【解决方案1】:

    首先,由于您使用引导图标并且它们仅使用 CSS content 属性,因此您无权访问其中的 fill 属性,因此它不会按预期工作,或者,您应该使用 colorfont-size 属性来实现您想要的。

    为了在 javascript 中使用它,您需要使用style 属性,然后在其中访问它们的属性(如colorfontSize。使用相同的解决方案,您可以使用font-size 属性更改它们的大小。

    这是上述方法的最终产品:

    document.addEventListener('DOMContentLoaded', function() {
      var heart = document.createElement('i')
      heart.className = 'bi bi-heart'
      document.querySelector('#posts').append(heart)
      heart.onclick = function() {
        this.className = 'bi bi-heart-fill'
        this.style.color = 'red'
        this.style.fontSize = '24px'
      }
    })
    <head>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
    </head>
    
    <body>
      <div id="posts"></div>
    </body>

    【讨论】:

      【解决方案2】:

      标签的内容可以视为文本,所以你应该使用“color”属性来改变颜色,使用“font-size”来让它变大,你可以在css上创建一个同时具有这个属性的类和单击图标后,将类分配给元素。

      CSS:

      .active { color: red; font-size: 24px }
      

      JS:

      (...)
      heart.onclick = function() {
        this.classList.add('active')
      }
      

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2012-10-01
      • 2023-03-04
      相关资源
      最近更新 更多