Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

滚定区域内,把子元素滚动到 父元素中间位置(如:可滚动横向 tab 滚动到中间位置) #21

Open
JslinSir opened this issue Jul 19, 2022 · 1 comment

Comments

@JslinSir
Copy link
Owner

// parentEl代表父元素,也就是设置了overflow为可滚动的元素
    // childEl代表需要滚动到父元素正中间的直接子元素

    // 水平滚动
    let x = childEl.offsetLeft - parentEl.clientWidth + parentEl.clientWidth/2 + childEl.clientWidth/2;
    parentEl.scrollTo({
        left: x,
        behavior: "smooth",
    });

    // 垂直滚动
    let y = childEl.offsetTop - parentEl.clientHeight + parentEl.clientHeight/2 + childEl.clientHeight/2;
    parentEl.scrollTo({
        top: y,
        behavior: "smooth",
    });
@JslinSir JslinSir changed the title 滚定区域内,把子元素滚动到 父元素中间位置 滚定区域内,把子元素滚动到 父元素中间位置(如:可滚动横向 tab 滚动到中间位置) Jul 28, 2022
@JslinSir
Copy link
Owner Author

// 小程序中使用示例
  async handleSelectTab(event){
      const { selectIndex } = this.data
     const { index } = event.currentTarget.dataset
     if(selectIndex!=index){
       const parentEl = await this.getNodeRef('.brand-cate-scroll',true)
       const childElAll = await this.getNodeRef(`.brand-cate-item`,true,'selectAll')
       const childEl = childElAll[index]
       const scrollX = childEl.left - parentEl.width + parentEl.width/2 + childEl.width/2;
       this.setData({ selectIndex:index,scrollX })
     }
    },

 
    getNodeRef(select,memo=false,selectType='select') {
      return new Promise((revose) => {
        if(memo && this[`_${select}_Rect`]){
          revose(this[`_${select}_Rect`]);
          return
        }
        const query = this.createSelectorQuery();
        query[selectType](select).boundingClientRect();
        query.exec((res) => {
          this[`_${select}_Rect`] = res[0]
          revose(res[0]);
        });
      });
    },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant