寫在前面
因最近項目需要制作一個聊天界面,對比后感覺MUI源碼內的im-chat.html文件對各種情況的處理比較的全面,因此,將整個頁面的邏輯從頭到尾理了一遍,希望有需求的小伙伴可以少走彎路,通過這個模板,可以根據我們自己需要的功能進行定制,如果不是很清楚(用詞不當)的地方,還請小伙伴們提出來,做相關修改,謝謝!
ps:理這種邏輯性的東西需要耐心,所以希望小伙伴能夠靜下心來慢慢理,任何代碼都是根據需求實現。所以,可以結合實際操作來看相關模塊。最后,求一波關注,哈哈!
相關引用
這個聊天框架基於MUI開發,正常引入相關文件后,還需引入如下文件:
- 圖片預覽的mui.imageviewer.css樣式文件,
- 處理圖片瀏覽的mui.imageViewer.js文件,
- 模板渲染的arttmpl.js文件;
代碼詳解
<body contextmenu="return false;">
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">chat (聊天窗口)</h1>
</header>
<pre id='h'></pre>
<script id='msg-template' type="text/template">
<% for(var i in record){ var item=record[i]; %>
<div class="msg-item <%= (item.sender=='self'?' msg-item-self':'') %>" msg-type='<%=(item.type)%>' msg-content='<%=(item.content)%>'>
<% if(item.sender=='self' ) { %>
<i class="msg-user mui-icon mui-icon-person"></i>
<% } else { %>
<img class="msg-user-img" src="../images/logo.png" alt="" />
<% } %>
<div class="msg-content">
<div class="msg-content-inner">
<% if(item.type=='text' ) { %>
<%=( item.content|| ' ') %>
<% } else if(item.type=='image' ) { %>
<img class="msg-content-image" src="<%=(item.content)%>" style="max-width: 100px;" />
<% } else if(item.type=='sound' ) { %>
<span class="mui-icon mui-icon-mic" style="font-size: 18px;font-weight: bold;"></span>
<span class="play-state">點擊播放</span>
<% } %>
</div>
<div class="msg-content-arrow"></div>
</div>
<div class="mui-item-clear"></div>
</div>
<% } %>
</script>
<div class="mui-content">
<div id='msg-list'>
</div>
</div>
<footer>
<div class="footer-left">
<i id='msg-image' class="mui-icon mui-icon-camera" style="font-size: 28px;"></i>
</div>
<div class="footer-center">
<textarea id='msg-text' type="text" class='input-text'></textarea>
<button id='msg-sound' type="button" class='input-sound' style="display: none;">按住說話</button>
</div>
<label for="" class="footer-right">
<i id='msg-type' class="mui-icon mui-icon-mic"></i>
</label>
</footer>
<div id='sound-alert' class="rprogress">
<div class="rschedule"></div>
<div class="r-sigh">!</div>
<div id="audio_tips" class="rsalert">手指上滑,取消發送</div>
</div>
<script src="../js/mui.min.js"></script>
<script src="../js/mui.imageViewer.js"></script>
<script src="../js/arttmpl.js"></script>
<script type="text/javascript" charset="utf-8">
(function($, doc) {
var MIN_SOUND_TIME = 800;
$.init({
gestureConfig: {
tap: true, //默認為true
doubletap: true, //默認為false
longtap: true, //默認為false
swipe: true, //默認為true
drag: true, //默認為true
hold: true, //默認為false,不監聽
release: true //默認為false,不監聽
}
});
template.config('escape', false);
//$.plusReady=function(fn){fn();};
$.plusReady(function() {
plus.webview.currentWebview().setStyle({
softinputMode: "adjustResize"
});
//強制彈出鍵盤
var showKeyboard = function() {
if ($.os.ios) {
var webView = plus.webview.currentWebview().nativeInstanceObject();
webView.plusCallMethod({
"setKeyboardDisplayRequiresUserAction": false
});
} else {
var Context = plus.android.importClass("android.content.Context");
var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
var main = plus.android.runtimeMainActivity();
var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//var view = ((ViewGroup)main.findViewById(android.R.id.content)).getChildAt(0);
imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
//alert("ll");
}
};
var record = [{
sender: 'zs',
type: 'text',
content: 'Hi,我是 MUI 小管家!'
}];
var ui = {
body: doc.querySelector('body'),
footer: doc.querySelector('footer'),
footerRight: doc.querySelector('.footer-right'),
footerLeft: doc.querySelector('.footer-left'),
btnMsgType: doc.querySelector('#msg-type'),
boxMsgText: doc.querySelector('#msg-text'),
boxMsgSound: doc.querySelector('#msg-sound'),
btnMsgImage: doc.querySelector('#msg-image'),
areaMsgList: doc.querySelector('#msg-list'),
boxSoundAlert: doc.querySelector('#sound-alert'),
h: doc.querySelector('#h'),
content: doc.querySelector('.mui-content')
};
//將文本框寬度賦值給h
ui.h.style.width = ui.boxMsgText.offsetWidth + 'px';
//alert(ui.boxMsgText.offsetWidth );
//讓文本框居中
var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
//語音輸入相關操作
var msgItemTap = function(msgItem, event) {
var msgType = msgItem.getAttribute('msg-type');
var msgContent = msgItem.getAttribute('msg-content')
if (msgType == 'sound') {
player = plus.audio.createPlayer(msgContent);
var playState = msgItem.querySelector('.play-state');
playState.innerText = '正在播放...';
player.play(function() {
playState.innerText = '點擊播放';
}, function(e) {
playState.innerText = '點擊播放';
});
}
};
//圖片預覽組件
var imageViewer = new $.ImageViewer('.msg-content-image', {
dbl: false
});
//綁定消息節點
var bindMsgList = function() {
//綁定數據:
/*tp.bind({
template: 'msg-template',
element: 'msg-list',
model: record
});*/
//將數據綁定到界面上
ui.areaMsgList.innerHTML = template('msg-template', {
"record": record
});
//拿到所有的聊天節點
var msgItems = ui.areaMsgList.querySelectorAll('.msg-item');
//因為document.querySelectorAll()返回的並不是我們想當然的數組,而是NodeList,對NodeList,它里面沒有.forEach方法,我們使用了這樣的方法進行循環:
//通過call將this綁定到msgItems(以[]下標的方式去遍歷msgItems)
[].forEach.call(msgItems, function(item, index) {
item.addEventListener('tap', function(event) {
//處理語音消息播放
msgItemTap(item, event);
}, false);
});
//查找所有符合條件的圖片
imageViewer.findAllImage();
//聊天界面的高度修改
ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
};
bindMsgList();
//平滑高度過渡
window.addEventListener('resize', function() {
ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
}, false);
//發送對象聲明
var send = function(msg) {
//將消息內容體push進record
record.push(msg);
//綁定消息節點
bindMsgList();
toRobot(msg.content);
};
var toRobot = function(info) {
var apiUrl = 'http://www.tuling123.com/openapi/api';
$.getJSON(apiUrl, {
"key": 'acfbca724ea1b5db96d2eef88ce677dc',
"info": info,
"userid": plus.device.uuid
}, function(data) {
//alert(JSON.stringify(data));
record.push({
sender: 'zs',
type: 'text',
content: data.text
});
bindMsgList();
});
};
//讓輸入框獲取焦點
function msgTextFocus() {
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
}
//解決長按“發送”按鈕,導致鍵盤關閉的問題;
ui.footerRight.addEventListener('touchstart', function(event) {
if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
msgTextFocus();
event.preventDefault();
}
});
//解決長按“發送”按鈕,導致鍵盤關閉的問題;
ui.footerRight.addEventListener('touchmove', function(event) {
if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
msgTextFocus();
event.preventDefault();
}
});
// ui.footerRight.addEventListener('touchcancel', function(event) {
// if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
// msgTextFocus();
// event.preventDefault();
// }
// });
// ui.footerRight.addEventListener('touchend', function(event) {
// if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
// msgTextFocus();
// event.preventDefault();
// }
// });
//長按離開屏幕時觸發
ui.footerRight.addEventListener('release', function(event) {
//當是文字時
if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
//showKeyboard();
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
// event.detail.gesture.preventDefault();
send({
sender: 'self',
type: 'text',
content: ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '<br/>')
});
ui.boxMsgText.value = '';
$.trigger(ui.boxMsgText, 'input', null);
}
//當是語音時
else if (ui.btnMsgType.classList.contains('mui-icon-mic')) {
ui.btnMsgType.classList.add('mui-icon-compose');
ui.btnMsgType.classList.remove('mui-icon-mic');
ui.boxMsgText.style.display = 'none';
ui.boxMsgSound.style.display = 'block';
ui.boxMsgText.blur();
document.body.focus();
}
//當是文本狀態時
else if (ui.btnMsgType.classList.contains('mui-icon-compose')) {
ui.btnMsgType.classList.add('mui-icon-mic');
ui.btnMsgType.classList.remove('mui-icon-compose');
ui.boxMsgSound.style.display = 'none';
ui.boxMsgText.style.display = 'block';
//--
//showKeyboard();
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
}
}, false);
//點擊左邊按鈕時
ui.footerLeft.addEventListener('tap', function(event) {
var btnArray = [{
title: "拍照"
}, {
title: "從相冊選擇"
}];
plus.nativeUI.actionSheet({
title: "選擇照片",
cancel: "取消",
buttons: btnArray
}, function(e) {
var index = e.index;
switch (index) {
case 0:
break;
case 1:
var cmr = plus.camera.getCamera();
cmr.captureImage(function(path) {
send({
sender: 'self',
type: 'image',
content: "file://" + plus.io.convertLocalFileSystemURL(path)
});
}, function(err) {});
break;
case 2:
plus.gallery.pick(function(path) {
send({
sender: 'self',
type: 'image',
content: path
});
}, function(err) {}, null);
break;
}
});
}, false);
//控制按住語音時的顯示與隱藏
var setSoundAlertVisable=function(show){
if(show){
ui.boxSoundAlert.style.display = 'block';
ui.boxSoundAlert.style.opacity = 1;
}else{
ui.boxSoundAlert.style.opacity = 0;
//fadeOut 完成再真正隱藏
setTimeout(function(){
ui.boxSoundAlert.style.display = 'none';
},200);
}
};
var recordCancel = false;
var recorder = null;
var audio_tips = document.getElementById("audio_tips");
var startTimestamp = null;
var stopTimestamp = null;
var stopTimer = null;
//按住說話時候觸發
ui.boxMsgSound.addEventListener('hold', function(event) {
recordCancel = false;
//如果有結束時間,清除定時器
if(stopTimer)clearTimeout(stopTimer);
//修改顯示文字
audio_tips.innerHTML = "手指上划,取消發送";
//移除rprogress-sigh
ui.boxSoundAlert.classList.remove('rprogress-sigh');
//顯示樣式
setSoundAlertVisable(true);
//獲取錄音對象 5+模塊
recorder = plus.audio.getRecorder();
if (recorder == null) {
plus.nativeUI.toast("不能獲取錄音對象");
return;
}
//記錄當前錄音時間
startTimestamp = (new Date()).getTime();
//保存錄音http://www.html5plus.org/doc/zh_cn/audio.html#plus.audio.RecordOption
recorder.record({
filename: "_doc/audio/"
}, function(path) {
if (recordCancel) return;
send({
sender: 'self',
type: 'sound',
content: path
});
}, function(e) {
plus.nativeUI.toast("錄音時出現異常: " + e.message);
});
}, false);
//監聽drag(拖動中)事件 上滑;下滑事件
ui.body.addEventListener('drag', function(event) {
//console.log('drag');
if (Math.abs(event.detail.deltaY) > 50) {
//此時沒有錄音操作執行 檢查recordCancel狀態
if (!recordCancel) {
recordCancel = true;
if (!audio_tips.classList.contains("cancel")) {
audio_tips.classList.add("cancel");
}
audio_tips.innerHTML = "松開手指,取消發送";
}
} else {
if (recordCancel) {
recordCancel = false;
if (audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
}
audio_tips.innerHTML = "手指上划,取消發送";
}
}
}, false);
//長按離開錄音節點時執行
ui.boxMsgSound.addEventListener('release', function(event) {
//console.log('release');
//初始化
if (audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
audio_tips.innerHTML = "手指上划,取消發送";
}
//判斷錄音是否小於800毫秒,若小於,則廢棄
stopTimestamp = (new Date()).getTime();
if (stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
audio_tips.innerHTML = "錄音時間太短";
ui.boxSoundAlert.classList.add('rprogress-sigh');
recordCancel = true;
stopTimer=setTimeout(function(){
setSoundAlertVisable(false);
},800);
}else{
setSoundAlertVisable(false);
}
//停止錄音模塊
recorder.stop();
}, false);
//阻止瀏覽器默認的事件冒泡
ui.boxMsgSound.addEventListener("touchstart", function(e) {
//console.log("start....");
e.preventDefault();
});
//監聽用戶輸入時觸發
ui.boxMsgText.addEventListener('input', function(event) {
//當輸入為空時去掉發送文字,當不為空時,顯示發送文字
ui.btnMsgType.classList[ui.boxMsgText.value == '' ? 'remove' : 'add']('mui-icon-paperplane');
//當用戶輸入值不為空時,設置自定義屬性for 賦值msg-text
ui.btnMsgType.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
//替換與正則表達式相匹配的值(轉義)
ui.h.innerText = ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '\n-') || '-';
//動態調整輸入框高度
ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
//調整顯示信息高度
ui.content.style.paddingBottom = ui.footer.style.height;
});
var focus = false;
//監聽用戶點擊發送時觸發
ui.boxMsgText.addEventListener('tap', function(event) {
//得到焦點
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 0);
focus = true;
setTimeout(function () {
focus = false;
},1000);
//阻止iOS2.0中的手勢事件:gesture事件
event.detail.gesture.preventDefault();
}, false);
//點擊消息列表,關閉鍵盤
ui.areaMsgList.addEventListener('click',function (event) {
if(!focus){
ui.boxMsgText.blur();
}
})
});
}(mui, document));
</script>
</body>