函数节流

上次又一次做了一个div固定的效果,考虑到onscroll会不停的执行。

var _b = $("#bottom");

    $(window).scroll(function(){
        var t = $(window).scrollTop(),
            str;
        console.log(t)
        if(t >= 200){
            str = {"position" : "fixed", "top" : 200 + "px", "right" : "0px"};
        }else{
            str = {"position" : "absolute", "top" : 500 + "px", "right" : "0px"};
        }
        _b.css(str);

    });

改变:

var processor = {
        timeoutId : null,

        // 实际进行处理的方法
        performProcessing : function(){
            var _b = $("#bottom");
            var i = 0;

            var t = $(window).scrollTop(),
                str;
            // console.log(t)
            if(t >= 200){
                str = {"position" : "fixed", "top" : 200 + "px", "right" : "0px"};
            }else{
                str = {"position" : "absolute", "top" : 500 + "px", "right" : "0px"};
            }
            _b.css(str);
            i++;
            console.log(i);
        },
        process : function(){
            clearTimeout(this.timeoutId);

            var that = this;
            this.timeoutId = setTimeout(function(){
                that.performProcessing();
            },500);
        }
    };
    // 尝试开始执行
    
    window.onscroll = function(){
        processor.process();
    };

很明显i 值变少了。。。那么onresize呢?

onresize的正常函数:

window.onresize = function(){
        var div = document.getElementById("myDiv");
        div.style.height = div.offsetWidth + 'px';
        console.log(div.offsetWidth);
    };

// 有两个问题会造成浏览器运行缓慢
// 1. 要计算offsetWidth 属性 首先:如果该元素或者页面上其他元素有非常复杂的css样式,那么这个过程会很复杂;其次:设置
// 某个元素的高度需要对页面进行回流来令改动生效
// 经测试,ie8,7在改变窗口大小时候 重复多次输出 div.offsetWidth

改良上面程序:

function throttle(method, context){// method : 要执行函数; context: 哪个作用域
        clearTimeout(method.tId);    // 首先清除之前设置的任何定时器
        method.tId = setTimeout(function(){
            method.call(context);// call(context) 确保方法在适当的环境中执行。如果没有第二个参数,在全局作用域执行改方法
        }, 1000);
    }

     function resizeDiv(){
        var div = document.getElementById("myDiv");
        div.style.height = div.offsetWidth + 'px';
        console.log(div.offsetWidth);
    };
    

    window.onresize = function(){
        throttle(resizeDiv);
    };

主要在ie87里面只输出两次。

原文地址:https://www.cnblogs.com/chuyu/p/3503628.html