简体   繁体   English

在悬停时更改glyphicon(引导程序)

[英]Changing glyphicon on hover (bootstrap)

I have an icon: 我有一个图标:

<span class='glyphicon glyphicon-heart-empty' aria-hidden='true'></span>

On hover, I want the glyphicon to change from heart-empty to: 悬停时,我希望glyphicon从heart-empty变为:

<span class='glyphicon glyphicon-heart' aria-hidden='true'></span>

And then if the user clicks the icon, the button will have the glyphicon heart and if the users clicks the icon again, it will put its state back to heart-empty . 然后,如果用户单击该图标,该按钮将带有glyphicon heart ;如果用户再次单击该图标,它将使其状态恢复为heart-empty

I have seen this JSfiddle here which on hover, displays an icon, whereas I want it to completely change the icon. 我在这里看到了这个JSfiddle 它悬停时显示一个图标,而我希望它完全更改该图标。 I have tried to use the approach in the JSfiddle, but it I cannot get it to do what I want. 我试图在JSfiddle中使用该方法,但是我无法让它做我想做的事情。

You can change the content property of the :before pseudo element to be the that of the icon you want. 您可以将:before伪元素的content属性更改为所需图标的属性。

Css CSS

span.clicked:before {
  content: "\e005";
} 

By adding a class when you click the icon you can then apply the new icon code. 通过在单击图标时添加一个类,然后可以应用新的图标代码。

JS JS

document.querySelector('span').addEventListener('click', function (e) {
    e.target.classList.toggle('clicked')
});

Demo 演示

You can see an example below 您可以在下面看到一个示例

<div>
<span class='glyphicon glyphicon-heart-empty' data-clicked="false" aria-hidden='true'></span> The Heart
</div>
<div>
<span class='glyphicon glyphicon-heart-empty' data-clicked="false" aria-hidden='true'></span> The Heart
</div>
<div>
<span class='glyphicon glyphicon-heart-empty' data-clicked="false" aria-hidden='true'></span> The Heart
</div>

and javascript part should be like 和JavaScript部分应该像

$("div").click(function() {
        var icon = $("span.glyphicon", this);
        var isClicked = icon.data("clicked");
    icon.data("clicked", !isClicked);
}).hover(function () {
    // hover in      
    var icon = $("span.glyphicon", this);
    var isClicked = icon.data("clicked");
    var remCls = isClicked ? "glyphicon-heart" : "glyphicon-heart-empty",
            addCls = isClicked ? "glyphicon-heart-empty" : "glyphicon-heart"
    icon
        .removeClass(remCls)
      .addClass(addCls);
}, function () {
    // hover out
    var icon = $("span.glyphicon", this);
    var isClicked = icon.data("clicked");
    var remCls = isClicked ? "glyphicon-heart-empty" : "glyphicon-heart",
            addCls = isClicked ? "glyphicon-heart" : "glyphicon-heart-empty"
    icon
        .removeClass(remCls)
      .addClass(addCls);
});

fiddle example: https://jsfiddle.net/88nara7m/1/ 小提琴示例: https : //jsfiddle.net/88nara7m/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM