连接字体真棒图标与字符串



所以我正在制作一个待办事项应用程序,而我试图添加字体真棒图标,以便在按下切换完成按钮时显示复选标记。我无法通过 HTML 添加它,因为列表通过 JS 动态更改。这是打印出已完成和未完成任务的 if/else。

  if (todo.completed === true) {
    todoTextDone = '(X)' + todo.todoText; // <i class="fa fa-check" aria-hidden="true"></i>
  } else {
    todoTextDone = '( )' + todo.todoText;
  }

我尝试过document.write,document.querySelectory,document.getElementById。我尝试创建一个 CSS 类并从 JS 中选择它,但它给了我一个对象集合错误。我尝试以 li 为目标,以便在 CSS 中有一个字体很棒的图标,但这也没有用!我是否试图以错误的方式使用它们?从理论上讲,document.write 方法应该有效,因为它将 HTML 插入到 DOM 中,所以我在这里缺少什么?

始终具有图标,然后根据项目的状态使用CSS将其隐藏(此处由类指示):

#toDo {
  padding: 0;
  list-style-type: none
}
#toDo li .fa {
  color: green
}
#toDo li.open .fa {
  opacity: 0
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<ul id="toDo">
  <li class="open"><i class="fa fa-check" aria-hidden="true"></i> First item</li>
  <li class="done"><i class="fa fa-check" aria-hidden="true"></i> Second item</li>
</ul>

顺便说一句,不要使用document.write()

首先,你必须创建元素

var iEl = document.createElement('i');  
iEl.style.className = "fa fa-check";  
document.getElementById("yourElementId").appendChild(iEl);  

此片段仅使用 CSS 和 Font-Awesome 样式表。如果您更喜欢其他格式,请参阅备忘单

片段

.chx {
  display: none;
}
.chx + label {
  color: #222;
  font-size: 18px;
  line-height: 100%;
}
.chx + label span {
  display: inline-block;
  width: 18px;
  height: 18px;
  vertical-align: baseline;
  cursor: pointer;
}
.chx + label span {
  background: #666;
  line-height: 100%;
}
.chx + label span {
  line-height: 100%;
}
#chx1:checked + label span:before {
  content: 'f00c';
  color: #F00;
  font-family: FontAwesome;
  font-weight: 900;
  font-size: 20px;
}
#chx2:checked + label span:before {
  content: 'f04b';
  color: #0ff;
  font-family: FontAwesome;
  font-weight: 900;
  font-size: 20px;
}
#chx2 + label span:before {
  content: 'f04c';
  color: #0ff;
  font-family: FontAwesome;
  font-weight: 900;
  font-size: 20px;
}
#chx2:checked + label span:after {
  content: 'Play';
}
#chx2 + label span:after {
  content: 'Pause';
  font-family: Verdana;
  margin-left: 5px;
}
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<input id='chx1' class='chx' type='checkbox'>
<label for='chx1'><span></span>
</label>
<hr>
<input id='chx2' class='chx' type='checkbox'>
<label for='chx2'><span></span>
</label>

最新更新