uni-app知识点:页面滚动到指定位置(即锚点实现)、设置背景颜色backgroundColor无效的问题、导航栏设置角标及动态控制修改角标数字、导航自定义按钮上的红点动态控制、动态修改tabBar的内容

一、页面滚动到指定位置(即实现锚点的功能)

  项目需求:在页面中,不管位于何处,点击评论按钮页面滚动到对应的评论位置。

  解决方案:将uniapp的uni.createSelectorQuery()方法与uni.pageScrollTo(OBJECT)方法结合使用。

更详细用法见官方文档:

uni.createSelectorQuery()方法: https://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery

uni.pageScrollTo(OBJECT)方法: https://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto

  实现思路如下:

uni.createSelectorQuery().select("#Comment").boundingClientRect((res)=>{
  uni.pageScrollTo({
    duration:0,
    scrollTop:res.top
  })
}).exec();

  但是你会发现,在页面没有滚动之前点击评论按钮可以直接滚动到评论,如果我页面有滚动,滚动距离就会出现偏差。

  这是因为滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离。

  最终实现代码如下:

toComment () {
  uni.createSelectorQuery().select('.article-box').boundingClientRect(data => {
    uni.createSelectorQuery().select('#Comment').boundingClientRect(res => {
      uni.pageScrollTo({
        scrollTop: res.top - data.top - 10
      })
    }).exec()
  }).exec()
}

  其中uni.createSelectorQuery()有一点需要注意的是下面这点:selectorQuery.in(component),它是将选择器的选取范围更改为自定义组件 component 内,返回一个 SelectorQuery 对象实例。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。

二、在uni-app项目中设置背景颜色和微信小程序设置 backgroundColor无效的问题

  在DCloud的官方提供的文档中写的方法是这样,如下

  但是实际设置了之后,没有作用,然后搜了一下说是因为 backgroundColor 指的窗体背景颜色,而不是页面的背景颜色,即窗体下拉刷新或上拉加载时露出的背景参考链接

  因此采用了直接在全局样式中设置page的样式(也可以写在app.vue中),如下:

page {
    background-color: #FFFFFF;
}

三、导航栏设置角标及动态控制修改角标数字

1、导航栏设置角标:

"buttons": [...,{
  "fontSrc": "/static/uni.ttf",
  "text": "\ue873",
  "fontSize": "22px",
  "color": "#999999",
  "badgeText": "0"
}],

  比较简单,直接按官网文档来即可。其中:badgeText 就是用来设置角标数字的。

2、动态修改角标数字

(1)创建角标:注意角标的index,只有app下才可以使用哦

// #ifdef APP-PLUS
let pages = getCurrentPages();
let page = pages[pages.length - 1];
let currentWebview = page.$getAppWebview();
currentWebview.setTitleNViewButtonBadge({ index: 0, text: '10' });  //text必须是string类型
// #endif

(2)移除角标

currentWebview.removeTitleNViewButtonBadge({ index: 0 });

四、导航的自定义按钮上的红点动态控制

  在page.json页面写好路由

"buttons": [{
    {
        "fontSrc": "/static/yticon.ttf",
        "text": "\ue744",
        "fontSize": "27",
        "color": "#303133",
        "background": "rgba(0,0,0,0)",
        "redDot": true  //红点
    }
]

  动态设置红点的显示与隐藏,index是按钮的下标

// #ifdef APP-PLUS
const pages = getCurrentPages();
const page = pages[pages.length - 1];
const currentWebview = page.$getAppWebview();
count == 0 
    ?currentWebview.hideTitleNViewButtonRedDot({index:1}) // 隐藏
    : currentWebview.showTitleNViewButtonRedDot({index:1}) // 显示
// #endif

五、动态修改tabBar的内容

  官方API:uni.setTabBarItem(OBJECT)

uni.setTabBarItem({
  index: 2,
  pagePath: "/pages/datalk/datalk",
  text: '数说',
  iconPath: "/static/tabBar/datalk.png",
  selectedIconPath: "/static/tabBar/datalked.png"
})

 

posted @ 2021-01-10 12:52  古兰精  阅读(5447)  评论(0编辑  收藏  举报