vue + element 页面滚动计算百分比 + 节流函数

html

js:

data() {
    return {
        scrollValue: 0,
    }
},
mounted() {
    window.addEventListener('scroll', this.handleScroll) // 监听页面滚动
},
beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
},
methods: {
// 获取页面滚动距离
    handleScroll() {
        // Progress bar
        var s = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
        // console.log(s)
        var body = document.body;
        // console.log(body)
        var html = document.documentElement;
        // console.log(html)
        var d = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
        // console.log(d)
        var c = window.innerHeight;
        // console.log(c);
        var position = (s / (d - c)) * 100;
        // 四舍五入取值
        this.scrollValue = Math.round(position)
    }
}

 添加节流函数

新建 utils 文件夹并新建 throttle.js 文件

throttle.js :

/**
 * 节流函数
 * fu 延时调用函数
 * interval 延迟多长时间
 */
export const _throttle = (fn, interval) => {
	var last;
	var timer;
	var interval = interval || 200;
	return function () {
		var th = this;
		var args = arguments;
		var now = +new Date();
		if (last && now - last < interval) {
			clearTimeout(timer);
			timer = setTimeout(function () {
				last = now;
				fn.apply(th, args);
			}, interval);
		} else {
			last = now;
			fn.apply(th, args);
		}
	}
};

开袋即食:

引入节流函数:

import { _throttle } from "@/utils/throttle.js"

使用节流函数:

mounted() {
     // 节流函数监听页面滚动
    window.addEventListener('scroll', _throttle(this.handleScroll,200))
    // window.addEventListener('scroll', this.handleScroll) // 监听页面滚动
},

你可能感兴趣的:(vue,javascript,vue.js,javascript,html)