抛出问题
一般会遇到在pc端编辑的 ueditor,需要同时在PC端及移动端展示。如果只是文字展示,大概没有什么需要注意的兼容性问题了。 但是ueditor可以编辑插入表格或者图片等,这些如果在移动端展示,可能就需要兼容了。
1、表格
表格在移动端展示的时候,边框都会消失,且格式变得很难看。
在移动端,把它兼容成左右可以滑动的效果。
2、图片
有些图片在PC端看着还可以,在移动端就会变得特别小,看不清楚
在移动端,给它加上一个点击图片放大缩小的效果。
解决方案:
我们从后端获取的数据是一串html片段,这时候我们需要用到一个插件。
cheerio , 它是用来解析字符串的一个插件。
实现表格滑动,使用另一个插件
better-scroll
解析字符串
<!--main.js-->
// 引入图片缩放插件
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
Vue.use(preview,{
fullscreenEl:false, //关闭全屏按钮
tapToClose: true,
closeEl:false,
})
<!--需要展示ueditor内容的页面-->
<template>
<div>
<div class="content-block" v-html="regHtml(detailData.content)"></div>
</div>
</template>
<script>
import Bscroll from 'better-scroll';
const cheerio = require('cheerio');
export default{
data(){
return {
imgPreview: {},
width: 784, // pc端展示的最大宽度
}
},
mounted() {
const _this = this;
this.$preview.on('imageLoadComplete',(e,item)=>{
console.log(this.$preview.self)
this.imgPreview = this.$preview.self
})
document.addEventListener('backbutton', function(e) {
// 在这里处理你的业务逻辑
e.preventDefault(); //backbutton事件的默认行为是回退历史记录,如果你想阻止默认的回退行为,那么可以通过preventDefault()实现
if(_this.imgPreview.close){
_this.imgPreview.close()
}
_this.$router.go(-1)
});
},
methods: {
regHtml(str) {
const _this = this;
const $ = cheerio.load(str);
// 屏幕宽度
const docEl = document.documentElement;
const clientWidth = docEl.clientWidth;
$('img').each((index, element) => {
// console.log($(element));
const attr = element.attribs;
$(element).attr('preview', index + 1);
// 如果不需要设置图片宽度,可以省略
if (attr.width) {
/*
* 判断width
* 宽度缩放比例
*/
const rate = attr.width / _this.width;
// 宽高比例
const wh = attr.width / attr.height;
$(element).attr('height', rate * clientWidth / wh);
$(element).attr('width', rate * clientWidth);
$(element).attr('style', '');
$(element).attr('class', 'img-skew');
}
});
$('table').each((index, element) => {
const attr = element.attribs;
$(element).attr('border', '1px solid #ccc');
const tableContent = $('<div class="table-content"></div>');
$(element).wrap(tableContent);
});
this.$nextTick(() => {
this.$root.$previewRefresh();
// 表格加横移
const tableList = document.getElementsByClassName('table-content');
const tlen = tableList.length;
for (let i = 0; i < tlen; i++) {
console.log(tableList[i]);
new Bscroll(tableList[i], {
'scrollX': true,
'eventPassthrough': 'vertical',
});
}
});
return $.html();
}
}
}
</script>
<style lang='scss'>
.img-skew{
max-width:100%;
}
</style>
最后
算是解决了在移动端不能适配的问题,如果还有更好的解决方案,欢迎留言。