繁体   English   中英

将鼠标悬停在javascript中的图释上时添加标题

[英]Add title when hovering on emoticons in javascript

我有此示例代码,用于在提交消息时用表情符号替换文本。 但是,当鼠标悬停在表情符号上时,我想在表情符号上添加标题,以标识用户使用了哪种表情符号,如何在当前代码中实现? 谢谢

<html>
 <head>
   <title>Testing Emoticon</title>
 </head>
 <body>
   <input type="text" name="message" id="message">
   <br><br>
 <div class="results"></div>
 <script language="javascript" src="./assets/js/jquery-1.11.3.min.js"></script>
 <script>
   function replaceEmoticons(text) {
     var emoticons = {
       ':-)' : 'smile.png',
       ':)'  : 'smile.png',
       ';)'  : 'wink.png',
       ';-)' : 'wink.png',
       ':P'  : 'tongue.png'
     }, url = "http://localhost/cb/2/assets/img/smileys/", patterns = [],
     metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

     // build a regex pattern for each defined property
     for (var i in emoticons) {
       if (emoticons.hasOwnProperty(i)){ // escape metacharacters
         patterns.push('('+i.replace(metachars, "\\$&")+')');
       }
     }

     // build the regular expression and replace
     return text.replace(new RegExp(patterns.join('|'),'g'), function(match) {
       return typeof emoticons[match] != 'undefined' ?
           '<img src="'+url+emoticons[match]+'"/>' :
           match;
     });
   }
 </script>
 <script>
   $('#message').keypress(function(e){
     if(e.which == 13){//Enter key pressed
       e.preventDefault();
       var emoticon = $('#message').val();
       $('.results').html(replaceEmoticons(emoticon));
     }
   });
 </script>
 </body>
</html>

解决的主要目的是,当您键入:)时,悬停的输出标题是来自smile.png smile ,这要归功于@PraveenKumar

另一个问题是我是否可以自定义标题,例如是否键入:P ,标题的输出可能是Stick Out Tongue tongue.png tongue ,而不是来自tongue.pngtongue

对于我的其他问题,我根据研究和试验错误测试提出了一个解决方案。

当我看到Ben Alman的这个javascript链接激发了我的主意。

因此,我重构了代码并得出以下结论:

我修改了json数组以添加更多数据。

var emoticons = {
  ':-)' : ['smile.png', 'Smile'],
  ':)'  : ['smile.png', 'Smile'],
  ';)'  : ['wink.png', 'Wink'],
  ';-)' : ['wink.png', 'Wink'],
  ':P'  : ['tongue.png', 'Stick Out Tongue']
}, url = "http://localhost/cb/2/assets/img/smileys/", patterns = [],
     metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

还有这部分功能来匹配我的新json数组:

// build the regular expression and replace
return text.replace(new RegExp(patterns.join('|'),'g'), function (match) {
  return typeof emoticons[match][0] != 'undefined' ?
      '<img src="'+url+emoticons[match][0]+'" title="' + emoticons[match][1] + '" />' :
      match;
});

现在,它确实可以根据我的需要工作。 万岁!

替换时添加:

return text.replace(new RegExp(patterns.join('|'),'g'), function(match) {
  return typeof emoticons[match] != 'undefined' ?
    '<img src="'+url+emoticons[match]+'" title="' + emoticons[match].substr(0, emoticons[match].length-4) + '" />' :
  match;
});

工作箱: http : //jsbin.com/cotefuwate/edit?output

暂无
暂无

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

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