首先官方文档中有介绍scroll-view的相关属性:
我们可以看到scroll-view中存在属性scroll-top="0"可以让滚动条回到顶部,但是实际操作中,我们往往需要在某些特定操作后让滚动条回到顶部
下面以点击按钮,让滚顶条回到顶部为例,写一个简单的实现代码:
scroll.wxml:
<view class="homes">
<!-- 小程序滚动容器 -->
<view class="home_container">
<!-- 左侧点击部分 假如右侧的滚动条不在顶部,点击按钮的时候,滚动条回到顶部-->
<view class="left_menu">
<button bindtap="backTop">点击回到顶部</button>
</view>
<!-- 右侧滚动条部分
其中 scroll-top="{{scrollTop}}"设置成变量,是因为如果直接在标签里写死的话,只会在页面初始化的时候,在顶部,等于没写
-->
<scroll-view scroll-top="{{scrollTop}}" scroll-y class="right_menu">
<view>1</view>
<view>2</view>
<view>3</view>
<view>4</view>
<view>5</view>
<view>6</view>
<view>7</view>
<view>8</view>
<view>9</view>
<view>10</view>
<view>11</view>
<view>12</view>
<view>13</view>
<view>14</view>
<view>15</view>
<view>16</view>
<view>17</view>
<view>18</view>
<view>19</view>
<view>20</view>
<view>21</view>
<view>22</view>
<view>23</view>
<view>24</view>
<view>25</view>
<view>26</view>
<view>27</view>
<view>28</view>
<view>29</view>
<view>30</view>
<view>31</view>
<view>32</view>
<view>33</view>
<view>34</view>
<view>35</view>
<view>36</view>
<view>37</view>
<view>38</view>
<view>39</view>
<view>40</view>
<view>41</view>
<view>42</view>
<view>43</view>
<view>44</view>
<view>45</view>
<view>46</view>
<view>47</view>
<view>48</view>
<view>49</view>
<view>50</view>
<view>51</view>
<view>52</view>
<view>53</view>
<view>54</view>
<view>55</view>
<view>56</view>
<view>57</view>
<view>58</view>
<view>59</view>
<view>60</view>
<view>61</view>
<view>62</view>
<view>63</view>
<view>64</view>
<view>65</view>
<view>66</view>
<view>67</view>
<view>68</view>
<view>69</view>
<view>70</view>
<view>71</view>
<view>72</view>
<view>73</view>
<view>74</view>
<view>75</view>
<view>76</view>
<view>77</view>
<view>78</view>
<view>79</view>
<view>80</view>
<view>81</view>
<view>82</view>
<view>83</view>
<view>84</view>
<view>85</view>
<view>86</view>
<view>87</view>
<view>88</view>
<view>89</view>
<view>90</view>
<view>91</view>
<view>92</view>
<view>93</view>
<view>94</view>
<view>95</view>
<view>96</view>
<view>97</view>
<view>98</view>
<view>99</view>
<view>100</view>
</scroll-view>
</view>
</view>
scroll.css:
/* 整个页面的高度为100% */
page{
height: 100%;
}
.homes{
height: 100%;
}
.home_container{
/* 1.容器总高度为100vh
2.上方搜索菜单为90rpx
3.下方tabBar菜单的高度不用减
*/
height: calc(100vh - 90rpx);
display: flex;
}
.left_menu{
flex:2;
background-color: sandybrown;
}
.right_menu{
flex:5;
background-color: springgreen;
}
scroll.js:
// pages/scroll/scroll.js
Page({
/**
* 页面的初始数据
*/
data: {
// 回到顶部变量
scrollTop:0
},
/**
* 点击按钮,滚动条回到页面顶部
*/
backTop:function(){
this.setData({
scrollTop:0
})
}
})