Fill color in icons
我是 css 和 jquery 的新手。我想在图标中填充颜色。例如,像 instagram 的心形图标(双击时会填充红色)。
我也使用了很棒的字体。所以我能够得到心形图标,但我无法按照我想要的方式填充颜色。我尝试更改背景颜色属性,但它也不起作用。
问题是,当用户点击心形图标时,它应该被红色填充。可以指导一下吗?
1
|
My html file
|
1
2 3 4 5 6 7 8 9 10 11 |
<!DOCTYPE html>
<html> <head> <script type=“text/javascript” src=“all.js”> </head> <body> |
1
|
all.js file is the file i downloaded for icons.
|
如果这不起作用,我应该使用什么来代替 font awesome?
- 单击后切换图像,使用红色心形图标。
- 你想要动画吗?因为那么您应该在互联网上搜索”心形按钮”并复制粘贴代码。例如:codepen.io/bnewton/pen/KrbLkx
- 或者只是一个简单的,比如 codepen.io/thebabydino/pen/MebVWR 或 codepen.io/thebabydino/pen/gMLeRz
- 需要一个简单的,非常感谢你..
你为什么要重新发明轮毂?您无需使用自己的样式来管理它。
事实上,FontAwesome 为每个图标提供了不同的类,例如,对于 fa-heart 图标,您可以使用 fa-heart 表示填充的心,使用 fa-heart-o 表示空心。
所以只需使用 jQuery 代码在图标的 click 事件上切换这两个类:
1
2 3 4 |
$(“#heart”).click(function() {
$(this).toggleClass(‘fa-heart-o’); $(this).toggleClass(‘fa-heart’); }); |
演示:
1
2 3 4 |
$(“#heart”).click(function() {
$(this).toggleClass(‘fa-heart-o’); $(this).toggleClass(‘fa-heart’); }); |
1
2 3 4 5 |
<link href=“https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css” rel=“stylesheet” />
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”> <i class=“fa fa-heart” id=“heart”> |
你可以给元素添加一个css类来设置它的外观。在我的示例中,我向元素添加了单击侦听器,并且只是切换了 CSS 类。
JS代码:
1
2 3 4 5 6 |
(function() {
const heart = document.getElementById(‘heart’); heart.addEventListener(‘click’, function() { heart.classList.toggle(‘red’); }); })(); |
示例链接:
你需要在图标中添加onlick函数,并创建一个函数来改变这个图标的颜色。
1
|
<i class=“far fa-heart” onclick=“changeColor()” id=“heart” style=“color: green; background-color: red”>
|
你的js应该是这样的:
1
2 3 4 5 |
function changeColor()
{ var icon = document.getElementById(‘heart’); icon.style.color =“red”; } |
使用 jquery toggleClass,您可以像这样从元素中的每个元素添加或删除类。
1
2 3 |
$(“#heart”).on(“click”, function() {
$(this).toggleClass(‘oldColor’, ‘newColor’); }); |
1
2 3 4 5 6 7 |
.newColor {
color: red; } .oldColor { |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”>
<!DOCTYPE html> <html> <head> <body> </html> |
- 这将不起作用,因为绿色是内联样式,并且您知道内联样式优先于类。
你可以像这样使用 onclick 属性:
1
|
<i class=“far fa-heart” id=“heart” onclick=“changeColor()” style=“color: green;”>
|
并在您的脚本区域或文件中定义如下函数:
1
2 |
function changeColor() {
document.getElementById(“heart”).style.color =“red”; } |
来源:https://www.codenong.com/49627444/