|
導讀微信小程序,簡稱小程序,英文名Mini Program,是一種不需要下載安裝即可使用的應用,它實現了應用“觸手可及”的夢想,用戶掃一掃或搜一下即可打開應用。小程序是一種不用下載就能使用的應用,也是一... 微信小程序,簡稱小程序,英文名Mini Program,是一種不需要下載安裝即可使用的應用,它實現了應用“觸手可及”的夢想,用戶掃一掃或搜一下即可打開應用。小程序是一種不用下載就能使用的應用,也是一項門檻非常高的創新,經過將近兩年的發展,已經構造了新的小程序開發環境和開發者生態。 這篇文章主要介紹了微信小程序 富文本轉文本實例詳解的相關資料,需要的朋友可以參考下微信小程序-富文本轉文本 最近小程序這么火,我也來搞搞。發現了一個惡心的問題。小程序沒有組件能支持富文本內容的,改接口又不太合適,于是有了這問,沒技術含量純粹記錄 首先我們看眼沒有被格式的富文本顯示: *.wxml內代碼。content是富文本內容 <view>
<text>{{content}}</text>
</view>顯示結果:
由以上圖片看到,小程序無法解析html文件 我們需要處理html富文本內容,讓其顯示好看點 下面直接上代碼了,主要功能就是利用js的replace 對富文本經行處理,大家可以看一下。一起優化,方便對富文本更好的處理。 convertHtmlToText: function convertHtmlToText(inputText) {
var returnText = "" + inputText;
returnText = returnText.replace(/<\/p>/ig, '\r\n');
returnText = returnText.replace(/<\/li>/ig, '\r\n');
returnText = returnText.replace(/<li>/ig, ' * ');
returnText = returnText.replace(/<\/ul>/ig, '\r\n');
//-- remove BR tags and replace them with line break
returnText = returnText.replace(/<br\s*[\/]?>/gi, "\r\n");
//-- remove P and A tags but preserve what's inside of them
returnText=returnText.replace(/<p.*?>/gi, "\r\n");
returnText=returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");
//-- remove all inside SCRIPT and STYLE tags
returnText=returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
returnText=returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
//-- remove all else
returnText=returnText.replace(/<(?:.|\s)*?>/g, "");
//-- get rid of more than 2 multiple line breaks:
returnText=returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");
//-- get rid of more than 2 spaces:
returnText = returnText.replace(/ +(?= )/g,'');
//-- get rid of html-encoded characters:
returnText=returnText.replace(/ /gi," ");
returnText=returnText.replace(/&/gi,"&");
returnText=returnText.replace(/"/gi,'"');
returnText=returnText.replace(/</gi,'<');
returnText=returnText.replace(/>/gi,'>');
return returnText;
}將上面代碼放入任意適合的小程序js文件中, 然后在需要處理數據的js文件里,引入文件,下面給出放入app.js文件中的調用示 例: var app = getApp()//獲取app小程序實例
onLoad: function (options) {
wx.request({
url: 'http://example.com/api' + options.id+'.json',
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
res.data.content = app.convertHtmlToText(res.data.content )
that.setData({
art: res.data.content
})
console.log(res.data)
}
})
}然后編譯刷新下,可以看到結果了:
這里可以繼續調整下css,使顯示得更好看點。 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持! 以上就是詳解微信小程序富文本轉文本實例代碼的詳細內容,更多請關注php中文網其它相關文章! 小程序是一種不需要下載安裝即可使用的應用,它實現了應用“觸手可及”的夢想,用戶掃一掃或者搜一下即可打開應用。 |
溫馨提示:喜歡本站的話,請收藏一下本站!