在JavaScript中切换心形HTML代码

4

我想添加一个心形图标作为按钮。 点击它应该切换填充/非填充状态。 我有两个选项 - ♡ 和 ❤ 但是当我将其作为文本进行比较时,无法实现。因为它显示为图像。 这是我的尝试:

function setMyFavorite(){
 alert('SetMyFavorite for '+ $("#heart").html());
 if($("#heart").html()=="♡"){
    $("#heart").html("❤");
 }

 if($("#heart").html()=="❤"){
        $("#heart").html("♡");
 }
}

这是我的HTML代码

<div id="heart" title="Set as Favorite" onclick="javascript:setMyFavorite();">&#9825;</div>

我该如何进行比较?

请问您能否附上您的HTML代码?这可能有助于解决您的问题。 - aMJay
如果您没有使用任何第三方CSS(如FontAwesome)并且只想使用JS,则可以根据data属性标记向<div>添加标志,基于该标志进行心形类型比较。 - Tanmay
4个回答

6
您可以使用Unicode字符进行比较。

const whiteHeart = '\u2661';
const blackHeart = '\u2665';
const button = document.querySelector('button');
button.addEventListener('click', toggle);

function toggle() {
  const like = button.textContent;
  if(like==whiteHeart) {
    button.textContent = blackHeart;
  } else {
    button.textContent = whiteHeart;
  }
}
<button></button>


6

像这样添加HTML按钮

<div>
  <i class="heart fa fa-heart-o"></i>
</div>

为此按钮添加CSS样式

.heart {
  font-size: 25px;
    color:red;
}

Javascript选择和取消选择按钮

$(".heart.fa").click(function() {
  $(this).toggleClass("fa-heart fa-heart-o");
});

在这里检查 jsfiddle 演示 链接


1
在不需要的情况下添加一个全新的库(尽管是一个很酷的库),似乎有些过度设计。 - Peter Abolins

0

最好的做法是:在按钮中使用 Font Awesome 图标。

有两种类型的图标,实心和轻量级,您可以在您的情况下使用其中之一。

因此,在切换时,您可以替换 Font Awesome 的类。

例如,这是您的按钮 <button class="fa fa-heart"></button>

因此,在切换时,您只需要替换按钮的类即可。

谢谢


0

类似这样的东西会给你一些想法 :) 玩得开心!

JavaScript:

<script>
function setMyFavorite(){
var elem = document.getElementById("circle");
//Gets the RGB value
var theColor = window.getComputedStyle(elem, null).getPropertyValue("background-color");
var hex = rgb2hex(theColor);
 if(hex =="#555555"){
    elem.style.backgroundColor = "#ffffff";
 }
else if(hex =="#ffffff"){
    elem.style.backgroundColor = "#555555";
}
//Convert RGB to Hex value
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
</script>

CSS:

 background-color: #555;
 border-radius: 50%;
 border-color:#555;
 border-style: solid;

请添加一些描述 - Mathews Sunny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接