js conceived emoji plugins from 0

Foreword:

Since the company's development projects need to use emoticon plugins, I have been on Baidu for a long time. Many emoticon plugins need to quote many js files, and there is no ready-made demo to use. There are also some plugins that quote a lot of pictures, and every expression needs to be used. Request again. For such a function, a lot of js and img have to be introduced, which is not worth the gain...

Therefore, the blogger himself coded a small "emoji plug-in" for direct use in future projects.

demo site: http://121.42.190.17/demo/emoji/src/demo.html

Features

Function: Pass the character format corresponding to the emoticon to the backend, the backend returns a string, and the front end parses the string and displays it into the corresponding emoticon on the page.

Instructions:

Configure the required parameters in option


var option = {

    emojiArray: ['angry'],     //填写表情字符串的数组,【注:源文件image下面的图标,只需要写红框内的字符串,详见下图】

    textareaId: 'emoji-editor',   //输入框的id

    loadId: 'load',                //加载表情的id

    emojiContainer: 'emojiContainer',     //存储表情的容器对象

    sendId: 'send',                      //发送信息的按钮 id

    emojiTranslateCls:'emoji-comment',    //需要转换成表情(img)的容器类名,只需要添加一个类,即可自动将:kissing_heart:渲染成表情~

};

/*调用方法*/

var text = new Emoji(option);

text.init();

js conceived emoji plugins from 0

General effect screenshot: (ui can be beautified according to their needs)

js conceived emoji plugins from 0

After clicking send, the data sent to the background is:

js conceived emoji plugins from 0

Three principles of emoticons:

How to display emoticons?

CSS Sprites (picture integration technology), first set the background icon, and then define the position, width, and height of each small icon to display the expression you want to display.

The problem encountered during the period: how to control the size of the displayed emoticon?

The first thing that comes to mind is the background-size method, but to redefine its position, it takes a lot of "stamina". Later, Liu Yinhua found a property transform: scale(1.5); to control the current element zoom ratio, haha, just one line of code. La~ Do you want a big or small expression, and the size is not satisfied? Get all one line of code

How to display emoticons in the input box?

At first, I selected the textarea of ​​input, but after adding the emoticon img "append" to the input box, the icon was not displayed. Later, I tried div, and after "append", I found that the emoticon can be displayed successfully, but the div cannot Enter text, to no avail...

Preliminary idea: Use input monitoring to add the textarea value to the div in real time. Similarly, this is also a waste of effort~ continue to explore...

Later found a very popular attribute. contenteditable=”true”, and happily chose contenteditable.

In the beginning, span is used to carry emoticons, but if div or span tags are used to place images, the contenteditable will be added to the final div/span by default..., so it will cause the emoticons to be entered and then text, the final text will be in In the last div/span, no text is displayed. Okay...I'm so tired...

Since div/span is not possible, use the img tag to carry the emoticon, and finally can enter normally.

[There is a problem with contenteditable. It supports rich text, is insecure, and has a bad user experience.

For example: when the user pastes, it will automatically bring the format, an example is as follows:

Here is a piece of code from an online god to remove the rich text function. For details, please refer to a blog post of a god

How to convert pictures and text?

At this time, we must use a powerful regular, first use html () to get the content, and then process the content.

Convert to text:

content.replace(/<img\b[^>]*/, imgObj[j])         //匹配所有的<img />,替换成相应的格式

imgObj.push(format + img[i].getAttribute("alt") + format);    //这里的format我使用的是:  所以就是类似这样 :fearful:   的格式

Convert to picture:


var keys = '\\+1|-1|100|109|1234|8ball|a|ab|abc|abcd|accept……'      //这里只列出部分

regex = new RegExp(':(' + keys + '):', 'g'),      // 匹配格式形如这样子的格式 :100:

$(obj[i]).html().replace(regex, emoji)   //替换

function emoji() {

    var key = arguments[1];

    return '<img src="" alt="' + key + '"class="emoji emoji_' + key + '"/>';    //返回对应的img格式

}

The code format of the entire plug-in is also a relatively common packaging method


//Emoji对象可变的属性

function Emoji(option) {

    this.emoji = option.emojiArray,

    this.textareaId = option.textareaId,

    this.loadId = option.loadId,

    this.sendId = option.sendId,

    this.emojiContainer = option.emojiContainer,

    this.emojiTranslateCls = option.emojiTranslateCls;

}

//Every time an instance is generated, the above attributes will be regenerated once, so that fixed methods will take up more memory. This is neither environmentally friendly nor efficient. Therefore, those unchanged properties and methods can be directly defined on the prototype object. At this time, all the fixed methods are actually the same memory address, pointing to the prototype object, so the operating efficiency is improved.


Emoji.prototype = {

    init: function () {   //放一些初始化的方法

        this.toEmoji();

        this.loadEmoji();

        this.bindEvent();

    },

    bindEvent: function () {},

    toEmoji: function () {},   //服务器数据转换成表情

    toText: function () {}   //转换成文字

    loadEmoji: function () {} //加载表情

}

Okay, even if such an emoji plug-in is finished, is it simple? At present, we need to rely on jquery for the time being, and if we have the energy, we will continue to make an O(∩_∩)O based on native js. The specific implementation code is on github.

Finally, attach the github address: https://github.com/beidan/emoji Welcome star, fork~~~

Guess you like

Origin blog.51cto.com/15080022/2588819