博客 (25)

以下是使用定时器每秒钟请求服务器,并在后一个请求的响应比前一个请求的响应先到达客户端时抛弃前一个请求的响应的代码:

(以 $.post 为例,$.ajax 同理)

let previousXHR = null; // 存储前一个请求的 jqXHR 对象

function sendRequest() {
  // 取消前一个请求
  if (previousXHR) {
    previousXHR.abort();
  }

  // 发送新的请求
  const currentXHR = $.post(url, data, function(response) {
    // 请求成功的回调函数
    console.log(response);
  });

  // 更新前一个请求的 jqXHR 对象
  previousXHR = currentXHR;
}

// 每秒钟发送请求
setInterval(sendRequest, 1000);


如果你用 axios,请参此文

xoyozo 3 个月前
235

不知道从哪个版本的 Chrome 或 Edge 开始,我们无法通过 ctrl+v 快捷键将时间格式的字符串粘贴到 type 为 date 的 input 框中,我们想办法用 JS 来实现。


方式一、监听 paste 事件:

const input = document.querySelector('input[type="date"]');
input.addEventListener('paste', (event) => {
    input.value = event.clipboardData.getData('text');
});

这段代码实现了从页面获取这个 input 元素,监听它的 paste 事件,然后将粘贴板的文本内容赋值给 input。

经测试,当焦点在“年”的位置时可以粘贴成功,但焦点在“月”或“日”上不会触发 paste 事件。


方式二、监听 keydown 事件:

const input = document.querySelector('input[type="date"]');
input.addEventListener('keydown', (event) => {
    if ((navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey) && event.key === 'v') {
        event.preventDefault();
        var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
        input.value = clipboardData.getData('text');
    }
});

测试发现报错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'getData')

Uncaught TypeError: Cannot read properties of undefined (reading 'clipboardData')

看来 event 中没有 clipboardData 对象,改为从 window.navigator 获取:

const input = document.querySelector('input[type="date"]');
input.addEventListener('keydown', (event) => {
    if ((navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey) && event.key === 'v') {
        event.preventDefault();
        window.navigator.clipboard.readText().then(text => {
            input.value = text;
        });
    }
});

缺点是需要用户授权:

image.png

仅第一次需要授权,如果用户拒绝,那么以后就默认拒绝了。


以上两种方式各有优缺点,选择一种适合你的方案就行。接下来继续完善。


兼容更多时间格式,并调整时区

<input type="date" /> 默认的日期格式是 yyyy-MM-dd,如果要兼容 yyyy-M-d 等格式,那么:

const parsedDate = new Date(text);
if (!isNaN(parsedDate.getTime())) {
    input.value = parsedDate.toLocaleDateString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split('/').reverse().join('-');
}

以 text 为“2023-4-20”举例,先转为 Date,如果成功,再转为英国时间格式“20-04-2023”,以“/”分隔,逆序,再以“-”连接,就变成了“2023-04-20”。

当然如果希望支持中文的年月日,可以先用正则表达式替换一下:

text = text.replace(/\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日\s*/, "$1-$2-$3");


处理页面上的所有 <input type="date" />

const inputs = document.querySelectorAll('input[type="date"]');
inputs.forEach((input) => {
    input.addEventListener(...);
});


封装为独立域

避免全局变量污染,使用 IIFE 函数表达式:

(function() {
  // 将代码放在这里
})();

或者封装为函数,在 jQuery 的 ready 中,或 Vue 的 mounted 中调用。


在 Vue 中使用

如果将粘贴板的值直接赋值到 input.value,在 Vue 中是不能同步更新 v-model 绑定的变量的,所以需要直接赋值给变量:

<div id="app">
    <input type="date" v-model="a" data-model="a" v-on:paste="fn_pasteToDateInput" />
    {{a}}
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
    const app = Vue.createApp({
        data: function () {
            return {
                a: null,
            }
        },
        methods: {
            fn_pasteToDateInput: function (event) {
                const text = event.clipboardData.getData('text');
                const parsedDate = new Date(text);
                if (!isNaN(parsedDate.getTime())) {
                    const att = event.target.getAttribute('data-model');
                    this[att] = parsedDate.toLocaleDateString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split('/').reverse().join('-');
                }
            },
        }
    });
    const vm = app.mount('#app');
</script>

示例中 <input /> 添加了 data- 属性,值同 v-model,并使用 getAttribute() 获取,利用 this 对象的属性名赋值。 

如果你的 a 中还有嵌套对象 b,那么 data- 属性填写 a.b,方法中以“.”分割逐级查找对象并赋值

let atts = att.split('.');
let target = this;
for (let i = 0; i < atts.length - 1; i++) {
    target = target[atts[i]];
}
this.$set(target, atts[atts.length - 1], text);


xoyozo 11 个月前
808

一般我们使用原生 JS 的时候使用 abort() 来取消 fetch 请求。

在使用 axios 发送请求时,如果我们想要取消请求,可以使用 axios 提供的 CancelToken 和 cancel 方法。下面是具体的实现步骤:

// 创建 CacnelToken 实例
const cancelTokenSource = axios.CancelToken.source();
// GET 方式请求
axios.get(url, {
    cancelToken: cancelTokenSource.token
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    console.log('An error occurred', thrown);
  }
});
// POST 方式请求
axios.post(url, data, {
    cancelToken: cancelTokenSource.token
});
// 取消请求
cancelTokenSource.cancel('请求被取消');

get 请求的时候,cancelToken 是放在第二个参数里;post 的时候,cancelToken 是放在第三个参数里。axios-0.27.2 中测试成功。

在即时响应的搜索框中可以这样处理:(vue3)

let cancelTokenSource;
const app = Vue.createApp({
    methods: {
        fn_list: function () {
            // 如果已有请求则取消
            cancelTokenSource && cancelTokenSource.cancel();
            // 创建一个新的请求
            cancelTokenSource = axios.CancelToken.source();
            axios.post(url, data, {
                cancelToken: cancelTokenSource.token
            }).then(function (response) {
                // 请求成功
            }).catch(function (error) {
                // 请求失败/取消
            });
        },
    }
});
const vm = app.mount('#app');


如果你用 jQuery,请参此文

xoyozo 1 年前
1,319

以 ASP.NET 6 返回 BadRequestObjectResult 为例。

public IActionResult Post()
{
    return BadRequest("友好的错误提示语");
}


axios

请求示例:

axios.post(url, {})
.then(function (response) {
    console.log(response.data);
})
.catch(function (error) {
    console.log(error.response.data);
});

error 对象:

{
  "message": "Request failed with status code 400",
  "name": "AxiosError",
  "code": "ERR_BAD_REQUEST",
  "status": 400,
  "response": {
    "data": "友好的错误提示语",
    "status": 400
  }
}


jQuery

请求示例:

$.ajax 对象形式

$.ajax({
    url: url,
    type: 'POST',
    data: {},
    success: function (data) {
        console.log(data)
    },
    error: function (jqXHR) {
        console.log(jqXHR.responseText)
    },
    complete: function () {
    },
});

$.ajax 事件处理形式(Event Handlers)jQuery 3+

$.ajax({
    url: url,
    type: 'POST',
    data: {},
})
    .done(function (data) {
        console.log(data)
    })
    .fail(function (jqXHR) {
        console.log(jqXHR.responseText)
    })
    .always(function () {
    });

$.get / $.post / $.delete

$.post(url, {}, function (data) {
    console.log(data)
})
    .done(function (data) {
        console.log(data)
    })
    .fail(function (jqXHR) {
        console.log(jqXHR.responseText)
    })
    .always(function () {
    });

jqXHR 对象:

{
  "readyState": 4,
  "responseText": "友好的错误提示语",
  "status": 400,
  "statusText": "error"
}


xoyozo 1 年前
1,384

原生判断

window.addEventListener('scroll', scroll)

function scroll() {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      
      if (scrollTop === 0) {
        console.log('滚动到顶了');
      }
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        console.log('滚动到底了');
      }
}

window.removeEventListener('scroll', scroll) // 移除滚动事件

scrollTop:文档在可视区上沿的位置距离文档顶部的距离

clientHeight:可视区的高度

scrollHeight:文档总高度

100:用于在滚动到底部之前提前加载内容(如瀑布流),提高用户体验,请自行修改数值(建议不小于 2 像素,以规避在部分浏览器上因获得值为小数时可能无法触发的问题)


jQuery 判断

window.addEventListener('scroll', scroll)

function scroll() {
    const doc_height = $(document).height();
    const scroll_top = $(document).scrollTop();
    const window_height = $(window).height();
    
    if (scroll_top === 0) {
      console.log('滚动到顶了');
    } else if (scroll_top + window_height >= doc_height - 100) {
      console.log('滚动到底了');
    }
}


xoyozo 1 年前
1,129
  • 在 vue 实例化之前,jQuery 绑定事件无效

xoyozo 2 年前
1,699

iPhone 或安卓上传的照片,可能因横向或纵向拍摄,导致上传后照片显示成 90 度、180 度、270 度角旋转,使用 C# 处理该照片时同样会遇到相同的问题。

解决的方案:

客户端使用 base64 显示图片,可按正常方向显示,且不通过服务端即时显示。关键代码:

$('#file_input').change(function (e) {
    if (e.target.files.length == 0) { return; }
    // file 转换为 base64
    var reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = function (event) {
        $('#myImg').attr('src', event.target.result).css({ width: 'auto', height: 'auto' });
    }
});
$('#myImg').on('load', function () {
    console.log('图片加载完成')
});

但 base64 字符串传递到服务端受请求大小限制(一般比直接 POST 文件要小)。所以显示图片的同时应即时使用 POST 方式上传图片(如 jquery.fileupload.js)。

当然如果是在微信中打开网页,使用 JS-SDK 的 wx.chooseImage() 返回的 localId 也可以在 <img /> 中正常显示,然后使用 wx.uploadImage() 上传到微信服务器并获取 serverId,在通过获取临时素材接口取回图片文件。

服务端如果需要处理该图片(缩放、裁切、旋转等),需要先读取照片的拍摄角度,旋正后,再进行处理,相关 C# 代码:

/// <summary>
/// 调整照片的原始拍摄旋转角度
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
private Image ImageRotateFlip(Image img)
{
    foreach (var prop in img.PropertyItems)
    {
        if (prop.Id == 0x112)
        {
            switch (prop.Value[0])
            {
                case 6: img.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
                case 3: img.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
                case 8: img.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
            }
            prop.Value[0] = 1;
        }
    }
    return img;
}
xoyozo 2 年前
2,215

前端引用 jquery、jquery-ui(或 jquery.ui.widget),以及 jquery.fileupload.js

$('#xxx').fileupload({
    url: 'FileUpload',
    add: function (e, data) {
        console.log('add', data);
        data.submit();
    },
    success: function (response, status) {
        console.log('success', response);
        toastr.success('上传成功!文件名:' + response);
    },
    error: function (error) {
        console.log('error', error);
        toastr.error("上传失败:" + error.responseText);
    }
});

服务端接收文件:

[HttpPost]
public ActionResult FileUpload([FromForm(Name = "files[]")] IFormFile file)
{
    try
    {
        return Ok(file.FileName);
    }
    catch(Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

此处 Name = "files[]" 值是由 <input type="file" name="这里定的" />

如果 input 没有指定 name,那么一般为 file[],或者在 Chrome 的开发者工具中,切换到 Network 标签页,选中 post 的目标请求,在 Headers 的 Form Data 中可以看到 name="xxx"。

xoyozo 4 年前
3,313

image.png

Unify Template 提供三种文件上传样式(如上图),“Plain File Input”和“File input”使用传统 <form /> 提交,“Advanced File input”调用组件实现。


ASP.NET Core 实现传统 <form /> 提交(以“Plain File Input”为例):

<form class="g-brd-around g-brd-gray-light-v4 g-pa-30 g-mb-30" id="form_avatar_upload" asp-action="AvatarUpload" enctype="multipart/form-data" method="post">
    <!-- Plain File Input -->
    <div class="form-group mb-0">
        <p>Plain File Input</p>
        <label class="u-file-attach-v2 g-color-gray-dark-v5 mb-0">
            <input id="fileAttachment" name="Avatar" type="file" onchange="form_avatar_upload.submit()">
            <i class="icon-cloud-upload g-font-size-16 g-pos-rel g-top-2 g-mr-5"></i>
            <span class="js-value">Attach file</span>
        </label>
    </div>
    <!-- End Plain File Input -->
</form>
public class AvatarUploadModel
{
    public IFormFile Avatar { get; set; }
}

[HttpPost]
public IActionResult AvatarUpload(AvatarUploadModel Item)
{
    return RedirectToAction("");
}


ASP.NET Core 调用 HSFileAttachment 组件实现:

<div class="form-group mb-20">
    <label class="g-mb-10">上传作品文件(包)</label>
    <input class="js-file-attachment_project" type="file" name="" id="file_project">
    <div style="display: none;" id="file_project_tip">
        <div class="u-file-attach-v3 g-mb-15" id="file_project_tip_content">
            <h3 class="g-font-size-16 g-color-gray-dark-v2 mb-0">拖曳文件到此处或者 <span class="g-color-primary">浏览你的电脑</span></h3>
            <p class="g-font-size-14 g-color-gray-light-v2 mb-0">
                如果您的作品包含多个文件,请添加到压缩包再上传
            </p>
            <p class="g-font-size-14 g-color-gray-light-v2 mb-0">
                支持的文件格式:
                <code>zip</code>
                <code>rar</code>
                <code>7z</code>
                <code>psd</code>
                <code>ai</code>
                <code>cdr</code>
                <code>jpg</code>
                <code>png</code>
                <code>gif</code>
                <code>tif</code>
                <code>webp</code>
            </p>
            <p class="g-font-size-14 g-color-gray-light-v2 mb-0">文件(包)的大小不能超过 <span>@options.Value.MaxSizeOfSigleFile_MB</span> MB</p>
        </div>
    </div>
    <small class="form-control-feedback">请上传作品文件</small>
</div>

<!-- JS Implementing Plugins -->
<script src="//cdn.***.com/unify/unify-v2.6.2/html/assets/vendor/jquery.filer/js/jquery.filer.min.js"></script>
<!-- JS Unify -->
<script src="//cdn.***.com/unify/unify-v2.6.2/html/assets/js/helpers/hs.focus-state.js"></script>
<script src="//cdn.***.com/unify/unify-v2.6.2/html/assets/js/components/hs.file-attachement.js"></script>
<!-- JS Plugins Init. -->
<script>
    $(document).on('ready', function () {
        // initialization of forms
        $.HSCore.components.HSFileAttachment.init('.js-file-attachment_project', {
            changeInput: $('#file_project_tip').html(),
            uploadFile: {
                url: url_UploadFile,
                data: { type: 'project' },
                success: function (data, element) {
                    console.log(data);

                    if (!data.success) {
                        var parent = element.find(".u-progress-bar-v1").parent();
                        element.find(".u-progress-bar-v1").fadeOut("slow", function () {
                            $("<div class=\"text-error g-px-10\"><i class=\"fa fa-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
                        });

                        alert(data.err_msg);
                    } else {
                        var parent = element.find(".u-progress-bar-v1").parent();
                        element.find(".u-progress-bar-v1").fadeOut("slow", function () {
                            $("<div class=\"text-success g-px-10\"><i class=\"fa fa-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
                        });

                        $('#file_project_tip_content').slideUp();

                        upload_project_id = data.id;
                    }
                }
            }
        });
        $.HSCore.helpers.HSFocusState.init();
    });
</script>
public IActionResult UploadFile([FromForm(Name = "[]")]IFormFile file, string type)
{
    return Ok(new { id = 1 });
}


xoyozo 4 年前
2,462

使用 JS 根据屏幕宽度来计算页面尺寸和字体大小并不是一个好办法。

rem 单位是跟随网页根元素的 font-size 改变而自动改变的,是一个相对的长度单位,非常适合在不同手机界面上自适应屏幕大小。 


一般的手机浏览器的默认字体大小为 16px。即:

:root { font-size: 16px; } /* 在 HTML 网页中,:root 选择器相当于 html */

也就是说,如果我定义一个宽度为 1rem,那么它的实际宽度为 16px。反过来说,如果设计稿宽度为 1000px,那么相当于 1000÷16=62.5‬rem。因此,我们设置一个 62.5rem 的宽度,即可正常显示 1000px 的设计效果。


为了适应不同屏幕尺寸的手机,只需按比例换算更改 :root 的 font-size 即可。这个比例是由“窗口宽度 ÷ 设计稿宽度”得到的,姑且称它为“窗设比”。

以 iPhone X 逻辑宽度 375px 为例,设计稿宽度 1000px 时,窗设比为:0.375。:root 的 font-size 将会被重置为 16 * 0.375 = 6px。上面的 62.5rem 宽度将对应 iPhone X 宽度为 62.5 * 6 = 375px,正好是屏幕逻辑宽度。


根据这个思路,理论上,我们只需要使用 CSS 将 :root 的 font-size 设置为 1px,然后使用 JS 重置为与“窗设比”相乘的积(本例中将被重置为 0.375px)。这样,我们可以不通过换算,只需要更改单位,将设计稿中的 500px 直接写入到 CSS 为 500rem,即可实现在 iPhone X 上显示逻辑宽度为(500 * 0.375 =)187.5px,即设计稿中的 1/2 宽度对应到屏幕上 1/2 的宽度。


实际上,部分安卓手机(如华为某旗舰机)不支持 :root 的 font-size 小于 12px,其它一些浏览器也会出现小于 12px 的文字以 12px 显示。


为了避免在任何环节出现小于 12px 的 font-size 值,且不增加设计稿尺寸到 CSS 数值的换算难度,我们设计了以下思路:

  1. 约定“设样比(设计稿的 px 值与 CSS 的 rem 值的比)”为 100;

  2. 使用 JS 将 :root 的 font-size 重置为“设样比”与“窗设比(窗口宽度 ÷ 设计稿宽度)”的乘积;

  3. 计算 CSS 时的 rem 值只需从设计稿中获取 px 值再除以“设样比”100 即可。 


这样做的另一个好处是,不用要求设计师必须按多少尺寸来设计,当然按主流尺寸来建议是可行的。


完整代码(jQuery 版):

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <title>Index</title>
    <style>
        body { margin: 0; text-align: center; }
        #app { margin: 0 auto; background-color: #EEE; display: none; }
        /* 长度计算方法:从设计稿获得长度(例如 160px),除以 px2rem 值(本例为 100),得到 1.6rem */
        .whole { background-color: #D84C40; width: 10rem; }
        .half { background-color: #3296FA; width: 5rem; }
        .half2 { background-color: #3296FA; width: 5rem; margin-left: 5rem; }
    </style>
</head>
<body>
    <div id="app">
        <div class="whole">100%</div>
        <div class="half">50%</div>
        <div class="half2">50%</div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        // [函数] 重置尺寸
        function fn_resize() {
            // 设计稿宽度(px)
            var designsWidth = 1000;
            // 约定的“设计稿 px 值与 CSS rem 值的比”,为方便计算,一般无需改动
            var px2rem = 100;
            // 限制 #app 的最大宽度为设计稿宽度
            $('#app').css('max-width', designsWidth).css('min-height', $(window).height());
            // 重置 :root 的 font-size
            var appWidth = Math.min($(window).width(), designsWidth);
            $(':root').css('font-size', px2rem * appWidth / designsWidth);
            $('#app').show();
        }
        // 页面加载完成后重置尺寸
        $(fn_resize);
        // 改变窗口大小时重置尺寸
        $(window).resize(fn_resize);
    </script>
</body>
</html>

完整代码(Vue2 版):

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <title>Index</title>
    <style>
        body { margin: 0; text-align: center; }
        #app { margin: 0 auto; background-color: #EEE; }
        /* 长度计算方法:从设计稿获得长度(例如 160px),除以 px2rem 值(本例为 100),得到 1.6rem */
        .whole { background-color: #D84C40; width: 10rem; }
        .half { background-color: #3296FA; width: 5rem; }
        .half2 { background-color: #3296FA; width: 5rem; margin-left: 5rem; }
    </style>
</head>
<body>
    <div id="app" v-bind:style="{ maxWidth: designsWidth + 'px', minHeight: appMinHeight + 'px' }" style="display: none;" v-show="appShow">
        <div class="whole">100%</div>
        <div class="half">50%</div>
        <div class="half2">50%</div>
        <div>appWidth: {{ appWidth }}</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                // 设计稿宽度(px)
                designsWidth: 1000,
                // 约定的“设计稿 px 值与 CSS rem 值的比”,为方便计算,一般无需改动
                px2rem: 100,
                // #app 的 width
                appWidth: 0, // 勿改
                appMinHeight: 0, // 勿改
                appShow: false, // 勿改
            },
            mounted: function () {
                // 页面加载完成后重置尺寸
                this.fn_resize();
                const that = this;
                // 改变窗口大小时重置尺寸
                window.onresize = () => {
                    return (() => {
                        console.log('RUN window.onresize()');
                        that.fn_resize();
                    })();
                };
            },
            watch: {
                // 侦听 appWidth 更改 root 的 font-size
                appWidth: function () {
                    console.log('RUN watch: appWidth');
                    var root = document.getElementsByTagName("html")[0];
                    root.style.fontSize = (this.px2rem * this.appWidth / this.designsWidth) + 'px';
                    this.appShow = true;
                }
            },
            methods: {
                fn_resize: function () {
                    console.log('RUN methods: fn_resize()');
                    this.appWidth = Math.min(document.body.clientWidth, this.designsWidth);
                    this.appMinHeight = document.documentElement.clientHeight;
                }
            }
        });
    </script>
</body>
</html>

完整代码(Vue3 版):

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <title>Index</title>
    <style>
        body { margin: 0; text-align: center; }
        #app > div { display: none; margin: 0 auto; background-color: #EEE; }
        /* 长度计算方法:从设计稿获得长度(例如 160px),除以 px2rem 值(本例为 100),得到 1.6rem */
        .whole { background-color: #D84C40; width: 10rem; }
        .half { background-color: #3296FA; width: 5rem; }
        .half2 { background-color: #3296FA; width: 5rem; margin-left: 5rem; }
    </style>
</head>
<body>
    <div id="app">
        <div style="display: none;" v-bind:style="{ maxWidth: designsWidth + 'px', minHeight: appMinHeight + 'px', display: appShow ? 'block' : 'none' }">
            <div class="whole">100%</div>
            <div class="half">50%</div>
            <div class="half2">50%</div>
            <div>appWidth: {{ appWidth }}</div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
    <script>
        const app = Vue.createApp({
            data: function () {
                return {
                    // 设计稿宽度(px)
                    designsWidth: 1000,
                    // 约定的“设计稿 px 值与 CSS rem 值的比”,为方便计算,一般无需改动
                    px2rem: 100,
                    // #app 的 width
                    appWidth: 0, // 勿改
                    appMinHeight: 0, // 勿改
                    appShow: false, // 勿改
                }
            },
            mounted: function () {
                // 页面加载完成后重置尺寸
                this.fn_resize();
                const that = this;
                // 改变窗口大小时重置尺寸
                window.onresize = () => {
                    return (() => {
                        console.log('RUN window.onresize()');
                        that.fn_resize();
                    })();
                };
            },
            watch: {
                // 侦听 appWidth 更改 root 的 font-size
                appWidth: function () {
                    console.log('RUN watch: appWidth');
                    var root = document.getElementsByTagName("html")[0];
                    root.style.fontSize = (this.px2rem * this.appWidth / this.designsWidth) + 'px';
                    this.appShow = true;
                }
            },
            methods: {
                fn_resize: function () {
                    console.log('RUN methods: fn_resize()');
                    this.appWidth = Math.min(document.body.clientWidth, this.designsWidth);
                    this.appMinHeight = document.documentElement.clientHeight;
                }
            }
        });
        const vm = app.mount('#app');
    </script>
</body>
</html>


示例中 CSS 初始 :root 的 font-size 为 16px(一个较小值,防止页面加载时瞬间出现大号文字影响用户体验),经过 fn_resize 后,:root 的 font-size 被设置为(100 * 375 / 1000 =)37.5px(iPhone X 中),那么宽度为 1000px 的设计稿中的 500px 换算到 CSS 中为 5rem,也即 37.5 * 5 = 187.5px,就是 iPhone X 的屏幕宽度的一半。

示例中 id 为 app 的 div 是用来在 PC 浏览器中限制页面内容最大宽度的(类似微信公众号发布的文章),如果网页不需要在 PC 端显示,jQuery 版代码中的 $('#app').width() 可以用 $(window).width() 来代替。

这个 div#app 一般设计有背景色,用于在宽度超过设计稿的设备上显示时区别于 body 的背景。但是当网页内容不超过一屏时,div#app 高度小于窗口,示例中与 appMinHeight 相关的代码就是为了解决这个问题。

示例中 div#app 隐藏/显示相关代码用于解决在页面加载初期由于 font-size 值变化引起的一闪而过的排版错乱。

image.png


最后补充一点,如果改变窗口大小时涉及执行耗时的操作,为避免页面卡顿,可以参考这篇文章添加函数防抖:https://xoyozo.net/Blog/Details/js-function-anti-shake

xoyozo 4 年前
4,413