学无先后,达者为师

网站首页 编程语言 正文

微信小程序实现滚动视图点击锚点跳转、点击左侧分栏时右侧对应内容置顶、左右分栏联动、setTimeout、findIndex、setData、parseInt、Math、random、forEach

作者:web半晨 更新时间: 2022-06-06 编程语言


1、关键代码

// 滚动时触发
bindscroll({detail: {scrollTop}}) {
	let that = this,
	titleContenData = that.data.titleContenData;

	// 防抖
	// timer定义在全局
	// 如果没有防抖会触发许多次
	// 对性能不友好
	if (timer !== undefined) clearTimeout(timer);

	timer = setTimeout(function () {
		// 当右侧滚动到顶部时强制赋值为0
		// 因为在滚动时一般获取到的数据是0-10的范围
		// 小概率会获取到0
		// 因为原先存储viewTop属性的第一个值就是0
		scrollTop = scrollTop < 10 ? 0 : scrollTop;
		let selectIndex = titleContenData.findIndex((item) => item.viewTop >= scrollTop);
		that.setData({
			// 设置高亮
			selectIndex,
			// 此属性联动左侧滚动条
			// 当右侧滚动时
			// 左侧也会相应的滚动
			// 只是滚动的距离不一样
			scrollTop: 5 * that.data.selectIndex
		});
	}, 100);
}

微信小程序有两个版本,此处展示柔和版的代码,还有一个版本是生硬版。两个版本的区别在于右侧滑动(滚动)时,页面动画和定位的位置不同,建议使用柔和版。两个版本存在的共同问题是,当内容倒数部分如果数据比较少,首次点击左侧倒数部分的标签会发生回跳到对应位置,此问题暂未解决


2、完整代码

1、gitee(码云) - develop分支 - leftAndRightColumnsSoft 文件夹-柔和版
2、gitee(码云) - develop分支 - leftAndRightColumnsStiff 文件夹-生硬版

原文链接:https://blog.csdn.net/weixin_51157081/article/details/124053442

栏目分类
最近更新