zoukankan      html  css  js  c++  java
  • 函数节流

    上次又一次做了一个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里面只输出两次。

  • 相关阅读:
    使用Dapper参数化查询(三) IN 查询
    cs窗体继承问题
    SVN使用教程总结(转载)
    celery——使用
    celery——简介及安装
    luffy——django中使用redis
    redis——redis入门(常用数据类型:l )
    redis——redis入门(二)
    redis——redis入门(常用数据类型:string hash)
    redis——redis入门(一)
  • 原文地址:https://www.cnblogs.com/chuyu/p/3503628.html
Copyright © 2011-2022 走看看