簡體   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