使用Jquery实施Hashtags [英] Implementing Hashtags using Jquery

查看:57
本文介绍了使用Jquery实施Hashtags的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想做的是,每当我写以#开头的任何内容时,标记字符串的颜色都应立即更改为其他颜色,例如蓝色.当我按空格键结束字符串时,颜色应变回黑色.我在一个内容可编辑的div上尝试了这样的逻辑:

What I want to do is basically is that whenever I write anything that starts with a #, the color of the tagged string should change to some other color, say blue, immediately. And when I press space to end the string, the color should change back to black. I tried a logic like this on a contenteditable div:

    if (# is pressed) 
    hashtagging = true
    append "<span>" to div

    if (space is pressed and hashtagging is true) 
    hashtagging = false
    append "</span>" to div

这无法正常工作.

推荐答案

应该执行以下操作:

$(function() {

    var hashtags = false;

    $(document).on('keydown', '#myInputField', function (e) {        
        arrow = {
            hashtag: 51,
            space: 32
        };

        var input_field = $(this);
        switch (e.which) {
            case arrow.hashtag:
                input_field.val(input_field.val() + "<span class='highlight'>");
                hashtags = true;
                break;
            case arrow.space:
                if(hashtags) {
                    input_field.val(input_field.val() + "</span>");
                    hashtags = false;
                }
                break;
        }

    });

});

现在,此代码检查是否按下了井号标签或空格,并在其上添加了带有样式类的span.检查keydown而不是keyup的原因是在将实际输入添加到文本字段之前添加标签.我使用文本字段作为输入,但是可以根据需要进行修改.

Now this code checks on keydown if the hashtag or space is pressed and adds a span with a class for styling to it. Reason for checking for keydown instead of keyup is to add the tags before the actual input is added to the textfield. I used a text-field as input, but modify it with whatever you need.

这篇关于使用Jquery实施Hashtags的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆