上篇文章 获取接口返回的一篇文章如何在轮播图中显示,并且完美适配分页(英文不截断单词)
本以为完美实现了功能,但是没想到打包出来后翻页不显示文字,多方了解后原来app端不支持js原生dom的操作,经过两天的修改最后app端也完美实现,上代码:
//下一页处理
async nextList(current) {
let that = this
//因为我的轮播第一张是图片,所以文章是从第二个开始的
if (current >= 1 && current < 5) {
//点击下一页的时候获取当前页面显示到了文章的哪一个字符,获取最后一个字符的索引
let mydom = `.p${current}`
let spandom = `.span${current}`
const texts = that.text[current - 1];
that.text[current - 1] = '';
let startPos = 0;
let endPos = texts.length;
let data = await getRect(mydom,that);
let rect = data;
while (startPos < endPos) {
let midPos = Math.floor((startPos + endPos) / 2);
console.log(midPos)
that.spantext[current - 1] = texts.substring(0, midPos + 1);
let spanRect = await getRect(spandom,that);
if (spanRect.bottom <= rect.bottom && spanRect.right <= rect.right) {
startPos = midPos + 1;
} else {
endPos = midPos;
}
}
that.text[current - 1] = texts;
//处理英文文章,截取的时候不截断单词
let pattern = /[a-zA-Z]/;
if (pattern.test(texts) && texts[startPos - 1] != " ") {
let str = texts.slice(0, startPos - 1)
let index = str.lastIndexOf(' ')
console.log(index)
startPos = index
}
// console.log(startPos)
// let index = getCharIndex1(element)
let index = startPos
console.log(index, texts[index])
//因为文章就一篇所以定义变量累计每一页的最后一个字符索引
that.textIndex += index
//引文点击上一页时要减去当前页的文字个数,所以存个数组
that.indexList.push(index)
//下一页显示的文章是当前页最后一个字的索引加1000个
that.text[current] = that.contentText.slice(that.textIndex, that.textIndex + 1000)
that.spantext[current] = that.contentText.slice(that.textIndex, that.textIndex + 1000)
}
}
const getRect = (selector,that) => {
return new Promise((resolve) => {
that.$nextTick(() => {
let view = uni.createSelectorQuery().select(selector);
view.boundingClientRect((res) => {
resolve(res);
}).exec();
})
})
}
主要是对获取元素的节点信息做了处理:
这边没有动态生成span标签,而是在结构里直接写了一个span标签
然后uniapp有获取节点信息的api
如果没看懂可以看一下上面的文章 或者 评论告诉我