如果用户写文本像:),:(等在textarea上,我希望它会在用户按下键盘空间后用表情符号替换此文本。(比如facebook替换表情符号)。
在我的下面的PHP代码中,按提交后替换表情符号。但是我想,它将用Clint-side java脚本替换表情符号。
我的php:
function smileys($text){
// Smiley to image
$smileys = array(
':)' => '<img src="smilies/smile.gif" border="0" alt="" />',
':-)' => '<img src="smilies/smile.gif" border="0" alt="" />',
':D' => '<img src="smilies/smile.gif" border="0" alt="" />',
':-(' => '<img src="smilies/angry.gif" border="0" alt="" />',
':-D' => '<img src="smilies/biggrin.gif" border="0" alt="" />',
'lol' => '<img src="smilies/biggrin.gif" border="0" alt="" />',
':-|' => '<img src="smilies/undecided.gif" border="0" alt="" />',
';-)' => '<img src="smilies/wink.gif" border="0" alt="" />',
);
// Now you need find and replace
foreach($smileys as $search => $replace){
$text = preg_replace("#(?<=\s|^)" . preg_quote($search) . "#", $replace, $text);
return $text;
}
}
// My others code
echo ''.smileys($description).'';
我收集了这个按下空格键后开始工作的JavaScript,但是我不知道如何编写这个完整的脚本来进行替换。
$('#comment').keypress(function(e)
{
if(e.keyCode == 32)
{
var comment = $('#comment').val()
//What will be here, I can't understand !!!
}
});
my textarea
<textarea name="comment" id="comment"></textarea>
答案 0 :(得分:0)
var smileys = {
':)': '<img src="smilies/smile.gif" border="0" alt="" />',
':-)': '<img src="smilies/smile.gif" border="0" alt="" />',
':D': '<img src="smilies/smile.gif" border="0" alt="" />',
':-(': '<img src="smilies/angry.gif" border="0" alt="" />',
':-D': '<img src="smilies/biggrin.gif" border="0" alt="" />',
'lol': '<img src="smilies/biggrin.gif" border="0" alt="" />',
':-|': '<img src="smilies/undecided.gif" border="0" alt="" />',
';-)': '<img src="smilies/wink.gif" border="0" alt="" />',
};
$(document).ready(function() {
$(".chat > textarea").attr("disabled", false); //enable the box on page load
$(".chat > textarea").keypress(function(e) {
$(".chat > div").html(smilyMe($(".chat > textarea").val()));
});
})
function smilyMe(msg) {
//smiley replace
return msg.replace(/(\:\)|\:-\)|\:D|\:-D|\blol\b|\:-\||\:-\(|\;-\))/g, function(all) {
return smileys[all] || all;
});
}
&#13;
div.chat {
width: 400px;
height: 200px;
border: 1px solid grey;
}
div.chat > div {
height: calc(100% - 50px);
width: 100%;
border-bottom: 1px dashed #939393;
padding: 2px 10px 10px 10px;
}
div.chat > div > div {
color: #939393;
font-size: 9px;
}
div.chat > textarea {
height: 50px;
width: 100%;
box-sizing: border-box;
border: 0px;
padding: 5px;
}
div {
box-sizing: border-box;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="chat">
<div>
<div>Preview</div>
</div>
<textarea disabled placeholder="Type your message here..."></textarea>
</div>
&#13;
使用我的smilyMe
功能。
但是,您无法将图像附加到文本区域。所以我实现了预览功能。