0

我需要 -

  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>

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

4

2 回答 2

2

首先,由于您使用引导图标并且它们只是使用 CSScontent属性,因此您无权访问其中的fill属性,因此它不会按预期工作,或者,您应该使用colorfont-size属性来实现您所期待的为了。

为了在 javascript 中使用它,您需要使用style属性,然后在其中访问它们的属性(如colorfontSizefont-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>

于 2021-11-28T15:21:55.870 回答
1

标签的内容可以被视为文本,因此您应该使用“color”属性来更改颜色,并使用“font-size”使其变大,您可以在css上创建一个具有此属性的类并分配该类单击图标后到元素。

CSS:

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

JS:

(...)
heart.onclick = function() {
  this.classList.add('active')
}
于 2021-11-28T15:23:30.577 回答