【小程序】指定元素滚动到中间
vue代码
<scroll-view scroll-x class="type_scroll" :scroll-left="cho_nu"><block v-for="(item, index) in vehicle_types" :key="index"><view :id="'type_item_' + index" :class="['type_item', index == active_popup_type && 'active']"@tap.stop="popup_type(index)"><text class="type_name">{{ item.name }}</text></view></block>
</scroll-view>
js代码
// 滚动到指定位置
scroll_to_cho: function (index) {console.log("scroll_to_cho", index);var that = this;var old_left = that.cho_nu;this.$nextTick(function () {setTimeout(function () {// 获取所有类型项的位置信息var query = uni.createSelectorQuery().in(that);query.selectAll(".type_scroll").scrollOffset(); //scrollLeftquery.selectAll(".type_scroll").boundingClientRect(); //widthquery.selectAll("#type_item_" + index).boundingClientRect(); //width leftquery.exec(function (rects) {if (!rects[0] ||rects[0].length == 0 ||!rects[1] ||rects[1].length == 0 ||!rects[2] ||rects[2].length == 0)return;var box_so = rects[0][0]; //滚动容器var box_rect = rects[1][0]; //滚动容器var el_rect = rects[2][0]; //子元素var center = (el_rect.width - box_rect.width) / 2;var calc = box_so.scrollLeft + el_rect.left + center;if (old_left != calc) {that.cho_nu = old_left;that.cho_nu = calc;}});}, 30);});
},
