---
title: "微信小程序--搜索框滚动到顶部时悬浮"
author: "hereson"
date: "2018-12-06T14:44:24Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2022-07-07T00:05:56Z"
id: 2434832
url: "https://hereson.iteye.com/blog/2434832"
---

```
<scroll-view style="width:100%;height: 100%;" scroll-y="true" bindscroll="scrollTopFun">
    <view class="{{top>130 ? 'topnav' : ''}}">
    <--这里写大于130，表示距离顶部130rpx时固定，可根据需要修改-->
        ...
    </view>
</scroll-view>
```

 wxss

```
.topnav{
    position: fixed;
    top: 85rpx;
    z-index:99;
    background: #fff;
    width: 100%;
}
```

 js

```
data = {
  top:0
}
//控制回到顶部按钮的显示与消失
scrollTopFun(e){
    let that = this;
    that.top = e.detail.scrollTop;
    that.$apply();
}
```

 

或者

```
onPageScroll:function(e){
		let that = this;
		that.setData({top: e.scrollTop });
},
```

 当页面滚动时导航条到达搜索栏下方时固定，向上滚动到导航条位置时又恢复原样。 

 参考：[askjava](http://www.askjava.cn/p/)