前置代码
var editor = document.getElementById('editContent');
function randomString(length) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
-
模块不可编辑
我们项目需要视频
,音频
,定位地址
,我直接使用<iframe>
嵌套页面,例如音频:
var insertAudio = function(url, title, time){
var src = 'http://xxx.com/audio.html?title=' + encodeURIComponent(title) + '&time=' + time + '&url=' + encodeURIComponent(url);
var id = 'audio_iframe_'+randomString(32)+'_'+new Date().getTime();
var html = '<p>' +
'<b style="position:fixed;left:-999px;" contenteditable="false">[音频]</b>' +
'<iframe type="audio" id="'+id+'" name="'+id+'" class="audio_iframe" frameborder="0" src="" data-title="' + title + '" data-time="' + time + '" data-url="' + url + '" data-state="0"></iframe>' +
'</p>';
document.execCommand('insertHTML', false, html);
}
ps: 也可以使用 contenteditable="false"
属性加载模块上
-
阻止粘贴格式
editor.addEventListener("paste", function(e){
e.preventDefault();
var clp = (e.originalEvent || e).clipboardData;
var text= clp.getData("text/plain"); // 粘贴的文本,带换行符
var html= clp.getData("text/html"); // 带样式的html标签
document.execCommand('insertText', false, text);
});
-
转小程序
目前项目使用 mpvue 框架,富文本使用 mpvue-wxParse
<div id="article_content" class="article pl15 pr15 pb15 rel">
<wxParse :content="contentHTML" @navigate="navigate" :start-handler="startHandler" />
<div class="playStop abs" :style="{left:playStopData.x,top:playStopData.y}" @click="stopAudio"></div>
</div>
因为小程序不支持<iframe>
标签,需要转成a标签(mpvue-wxParse
只有<a>
与<img>
才有事件)
...
data() {
myAudio: null,
mp3Id: '',
playStopData: {
x: '-999px',
y: '-999px'
}
},
...
mounted(){
// 初始化音频
this.myAudio = wx.createInnerAudioContext();
this.myAudio.autoplay = true;
this.mp3Id = '';
},
methods: {
...
startHandler(node, results){
if(node.tag=='iframe'){
if(node.attr.class=='audio_iframe'){
node.attr.href = JSON.stringify({
type: 'audio',
src: node.attr['data-url'],
name: node.attr['data-title'].join(''),
id: node.attr.name
});
node.tag = 'a';
node.nodes = [{
node: 'text',
text: node.attr['data-title'].join('')
}]
node.classStr = `audio_iframe a`;
}
}
},
navigate(href, e){
try {
const data = JSON.parse(href);
if(data.type=='audio'){
if(data.id!=this.mp3Id){
this.mp3Id = data.id;
this.myAudio.src = data.src;
}
this.myAudio.play();
// 显示播放状态
const { offsetLeft, offsetTop } = e.mp.currentTarget;
this.playStopData = {
x: `${offsetLeft}px`,
y: `${offsetTop}px`
}
}
} catch (error) {
}
},
stopAudio(){
this.myAudio.pause();
this.playStopData = {
x: '-999px',
y: '-999px'
}
}
}
网友评论