scroll()、client()函数封装

!!!都是针对浏览器的

scroll()函数封装,解决scrollTop、scrollLeft的兼容性问题
client()函数封装,解决clientWidth、clientLeft的兼容性问题

 window.onscroll = function () {
            console.log(scroll().top);
            console.log(scroll().left);
        }

        function scroll(){      
        
 			 //简单封装(实际工作使用)
           return {
           
                "top": window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
                
                "left":  window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
            }
        }
   //新事件:浏览器大小变化事件(浏览器哪怕大小变化1px也会触动这个事件)
    window.onresize = function () {
        document.title = client().width + "    "+ client().height;
    }

    //获取屏幕可视区域的宽高
    function client(){
        if(window.innerHeight !== undefined){
            return {
                "width": window.innerWidth,
                "height": window.innerHeight
            }
        }else if(document.compatMode === "CSS1Compat"){
            return {
                "width": document.documentElement.clientWidth,
                "height": document.documentElement.clientHeight
            }
        }else{
            return {
                "width": document.body.clientWidth,
                "height": document.body.clientHeight
            }
        }
    }
防抖和节流是两种常用的函数优化技术,可以用来限制函数的执行频率,提高性能和用户体验。 防抖函数的作用是在短时间内连续触发同一事件时,只执行最后一次操作,而忽略之前的操作。可以用于处理频繁触发的事件,比如窗口大小改变、输入框输入等。 下面是一个简单的防抖函数封装示例: ```javascript function debounce(func, delay) { let timer = null; return function(...args) { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, delay); }; } ``` 使用方式示例: ```javascript function handleInput() { // 处理输入事件 } const debouncedHandleInput = debounce(handleInput, 300); // 创建防抖函数 inputElement.addEventListener('input', debouncedHandleInput); // 绑定防抖函数到输入框的输入事件 ``` 节流函数的作用是在一定时间间隔内只执行一次操作,可以用于处理高频率触发的事件,比如滚动事件、鼠标移动事件等。 下面是一个简单的节流函数封装示例: ```javascript function throttle(func, delay) { let timer = null; return function(...args) { if (timer) return; timer = setTimeout(() => { func.apply(this, args); timer = null; }, delay); }; } ``` 使用方式示例: ```javascript function handleScroll() { // 处理滚动事件 } const throttledHandleScroll = throttle(handleScroll, 300); // 创建节流函数 window.addEventListener('scroll', throttledHandleScroll); // 绑定节流函数到窗口的滚动事件 ``` 以上是基本的防抖和节流函数封装示例,可以根据实际需求进行调整和扩展。希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值