美文网首页小程序
小程序offsetTop,元素节点信息获取

小程序offsetTop,元素节点信息获取

作者: ThisWu | 来源:发表于2018-09-20 16:13 被阅读0次

业务需求需要做一个滑动的时候,如果超出滑动范围样式就需要改变。
当时听到这个需求的时候,第一反应就是在小程序不好做,因为小程序里面没有dom,所以没办法获取位偏移的值(offset)

注:
当然你的业务需求不够繁琐的时候,如果可以使用“scroll-view”这个标签的时候,这块的业务也是很简单的。

    小程序官方提供了一个api  wx.createSelectorQuery()
     它会返回一个 SelectorQuery 对象实例。

代码:

          const query = wx.createSelectorQuery()
          query.select('#the-id').boundingClientRect()
          query.selectViewport().scrollOffset()
          query.exec(function(res){
                res[0].top       // #the-id节点的上边界坐标
                res[1].scrollTop // 显示区域的竖直滚动位置
            })

        boundingClientRect()这个api可以获取当前元素的宽高
        wx.createSelectorQuery().select('#the-id').boundingClientRect().exec(function (res) {
              var height = res[0].height
                // console.log(height);

              }
          })

这个api个人感觉还是蛮实用的(目前只使用到这两个功能),有兴趣深入的研究
官方地址:https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createSelectorQuery.html?search-key=wx.createSelectorQuery()

相关文章

网友评论

    本文标题:小程序offsetTop,元素节点信息获取

    本文链接:https://www.haomeiwen.com/subject/fixnnftx.html