卤煮节流实现移动端自适应开发

本文介绍了一种使用自执行匿名函数实现的响应式网页布局方案,通过调整视口和字体大小确保不同屏幕尺寸下的一致显示效果。此外,还实现了一个节流函数以优化窗口调整大小事件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 自执行匿名函数,随着屏幕大小的变化而变化 */
(function () {
    // deicePixelRatio :设备像素
    var scale = 1 / devicePixelRatio;
    //设置meta 压缩界面 模拟设备的高分辨率
    document.querySelector('meta[name="viewport"]').setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');

    //debounce 为节流函数,自己实现。或者引入underscoure即可。
    /* Begin */
    var _ = function(obj) {
        if (obj instanceof _) return obj;
        if (!(this instanceof _)) return new _(obj);
        this._wrapped = obj;
    };
    _.now = Date.now || function() {
            return new Date().getTime();
    };
    _.debounce = function(func, wait, immediate) {
        var timeout, args, context, timestamp, result;

        var later = function() {
            var last = _.now() - timestamp;

            if (last < wait && last >= 0) {
                timeout = setTimeout(later, wait - last);
            } else {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                    if (!timeout) context = args = null;
                }
            }
        };
        return function() {
            context = this;
            args = arguments;
            timestamp = _.now();
            var callNow = immediate && !timeout;
            if (!timeout) timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
                context = args = null;
            }
            return result;
        };
    };
    /* End */

    var reSize = _.debounce(function () {
        var deviceWidth = document.documentElement.clientWidth > 750 ? 750 : document.documentElement.clientWidth;
        //按照750像素下字体为100px的标准来,得到一个字体缩放比例值 7.5
        document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px';
        console.log(document.documentElement.style.fontSize);
    }, 50);
    window.onresize = reSize;
})();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值