JavaScript工具类代码

1. 判断是否为移动端

function isMobile() {
    return /Mobi|Android|iPhone/i.test(navigator.userAgent);
}

2. 获取元素距离页面顶部的距离

function getOffsetTop(el) {
    let offset = 0;
    while (el) {
        offset += el.offsetTop;
        el = el.offsetParent;
    }
    return offset;
}

3. 防抖函数 debounce

function debounce(fn, delay = 300) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

4. 节流函数 throttle

function throttle(fn, delay = 300) {
    let last = 0;
    return function (...args) {
        const now = Date.now();
        if (now - last > delay) {
            last = now;
            fn.apply(this, args);
        }
    };
}

5. 复制文本到剪贴板

function copyToClipboard(text) {
    navigator.clipboard.writeText(text);
}

6. 平滑滚动到页面顶部

function scrollToTop() {
    window.scrollTo({top: 0, behavior: 'smooth'});
}

7. 判断对象是否为空

function isEmptyObject(obj) {
    return Object.keys(obj).length === 0 && obj.constructor === Object;
}

8. 数组去重

function unique(arr) {
    return [...new Set(arr)];
}

9. 生成随机颜色

function randomColor() {
    return `#${Math.random().toString(16).slice(2, 8)}`;
}

10. 获取 URL 查询参数

function getQueryParam(name) {
    return new URLSearchParams(window.location.search).get(name);
}

11. 判断是否为闰年

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

12. 数组乱序(洗牌算法)

function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

13. 获取 cookie

function getCookie(name) {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? decodeURIComponent(match[2]) : null;
}

14. 设置 cookie

function setCookie(name, value, days = 7) {
    const d = new Date();
    d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(value)};expires=${d.toUTCString()};path=/`;
}

15. 删除 cookie

function deleteCookie(name) {
    setCookie(name, '', -1);
}

16. 判断元素是否在可视区域

function isInViewport(el) {
    const rect = el.getBoundingClientRect();
    return rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth;
}

17. 获取当前时间字符串

function getTimeString() {
    return new Date().toLocaleString();
}

18. 监听元素尺寸变化(ResizeObserver)

const ro = new ResizeObserver(entries => {
    for (let entry of entries) {
        console.log('size changed:', entry.contentRect);
    }
});
ro.observe(document.querySelector('#app'));

19. 判断浏览器类型

function getBrowser() {
    const ua = navigator.userAgent;
    if (/chrome/i.test(ua)) return 'Chrome';
    if (/firefox/i.test(ua)) return 'Firefox';
    if (/safari/i.test(ua)) return 'Safari';
    if (/msie|trident/i.test(ua)) return 'IE';
    return 'Unknown';
}

20. 监听页面可见性变化

document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        console.log('页面不可见');
    } else {
        console.log('页面可见');
    }
});

21. 判断图片是否加载完成

function isImageLoaded(img) {
    return img.complete && img.naturalWidth !== 0;
}

22. 获取元素样式

function getStyle(el, prop) {
    return window.getComputedStyle(el)[prop];
}

23. 监听粘贴事件并获取内容

document.addEventListener('paste', e => {
    const text = e.clipboardData.getData('text');
    console.log('粘贴内容:', text);
});

24. 判断字符串是否为 JSON

function isJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch {
        return false;
    }
}

25. 生成指定范围的随机整数

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

26. 监听窗口尺寸变化

window.addEventListener('resize', () => {
    console.log('窗口尺寸变化:', window.innerWidth, window.innerHeight);
});

27. 判断邮箱格式

function isEmail(str) {
    return /^[\w.-]+@[\w.-]+\.\w+$/.test(str);
}

28. 判断手机号格式(中国)

function isPhone(str) {
    return /^1[3-9]\d{9}$/.test(str);
}

29. 计算两个日期相差天数

function diffDays(date1, date2) {
    const t1 = new Date(date1).getTime();
    const t2 = new Date(date2).getTime();
    return Math.abs(Math.floor((t2 - t1) / (24 * 3600 * 1000)));
}

30. 监听键盘按键

document.addEventListener('keydown', e => {
    console.log('按下了:', e.key);
});

31. 获取页面滚动距离

function getScrollTop() {
    return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}

32. 判断是否为数字

function isNumber(val) {
    return typeof val === 'number' && !isNaN(val);
}

33. 生成唯一ID(时间戳+随机数)

function uniqueId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}

34. 监听鼠标右键菜单

document.addEventListener('contextmenu', e => {
    e.preventDefault();
    console.log('右键菜单被触发');
});

35. 判断是否为函数

function isFunction(val) {
    return typeof val === 'function';
}

36. 获取本地存储 localStorage

function getItemByLocal(key) {
    return localStorage.getItem(key);
}

37. 设置本地存储 localStorage

function setItemByLocal(key, value) {
    localStorage.setItem(key, value);
}

38. 删除本地存储 localStorage

function removeItemLocal(key) {
    localStorage.removeItem(key);
}

39. 判断是否为 Promise

function isPromise(obj) {
    return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}

40. 获取当前页面路径

function getPath() {
    return window.location.pathname;
}

41. 监听剪贴板复制事件

document.addEventListener('copy', e => {
    console.log('内容已复制到剪贴板');
});

42. 判断是否为数组

function isArray(val) {
    return Array.isArray(val);
}

43. 获取元素宽高

function getSize(el) {
    return {width: el.offsetWidth, height: el.offsetHeight};
}

44. 判断是否为布尔值

function isBoolean(val) {
    return typeof val === 'boolean';
}

45. 监听页面滚动事件

window.addEventListener('scroll', () => {
    console.log('页面滚动了');
});

46. 判断是否为对象

function isObject(val) {
    return val !== null && typeof val === 'object' && !Array.isArray(val);
}

47. 获取当前域名

function getHost() {
    return window.location.host;
}

48. 判断是否为空字符串

function isEmptyTirm(str) {
    return typeof str === 'string' && str.trim() === '';
}

49. 监听窗口获得/失去焦点

window.addEventListener('focus', () => console.log('获得焦点'));
window.addEventListener('blur', () => console.log('失去焦点'));

50. 判断是否为 DOM 元素

function isElement(obj) {
    return obj instanceof Element;
}

TypeScript中用for in遍历对象的属性

ts遍历对象报错误:

TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ a: number; b: number; }’.   No index signature with a parameter of type ‘string’ was found on type ‘{ a: number; b: number; }’.

代码:

let arr = {
  a: 1,
  b: 2
};

for (const n in arr) {
  console.log(n, arr[n]);
}

解决办法为修改tsconfig.json,允许索引:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

 

 

 

 

chroem 89+ A标签打开新窗口导致sessionStorage失效

localStorage作用范围:本地存储,关闭浏览器后,数据依然会保存。同源浏览器窗口可以共享使用localStorage存储的数据。

sessionStorage作用范围:只存在于当前会话页面,当会话结束后,数据也随之销毁,在不同的浏览器窗口中共享。也就是存在于当前浏览器页面,页面关闭,数据也会删除。(注意:通过鼠标右键打开的新标签无法共享sessionStorage)

而这块对于sessionStorage可能一直存在一个误区,在Chrome浏览器89版本前,当前会话页面指的是当浏览器窗口没有关闭时,窗口内同域网站可以共享此数据(同源浏览器多个窗口不共享),当页面全部关闭或窗口关闭后,sessionStorage数据会被摧毁,所以你用a标签跳转还是js跳转都会共享sessionStorage。

而在2021年3月初Chrome浏览器进行了批量更新,更新到89版本后,通过a标签target=”_blank”跳转到新页面时sessionStorage就会丢失。Chrome这一更新可能会导致很多网站的sessionStorage丢失,页面可能直接就崩掉了。

解决办法如下:

1、最简单的解决办法 – a标签添加属性 rel=”opener”

<a href="http://xxx" target="_blank" rel="opener">Link</a>

 

angular directives scope

以前学过,但是忘记了,所以重新记录一篇文章。

directive中的restrict属性,来决定这个指令是作为标签(E)、属性(A)、属性值(C)、还是注释(M)。

1、false(默认值):直接使用父scope。比较“危险”。

可以理解成指令内部并没有一个新的scope,它和指令以外的代码共享同一个scope。

2、true:继承父scope

 

 

3、{ }:创建一个新的“隔离”scope,但仍可与父scope通信

隔离的scope,通常用于创建可复用的指令,也就是它不用管父scope中的model。然而虽然说是“隔离”,但通常我们还是需要让这个子scope跟父scope中的变量进行绑定。绑定的策略有3种:

  • @:单向绑定,外部scope能够影响内部scope,但反过来不成立
  • =:双向绑定,外部scope和内部scope的model能够相互改变
  • &:把内部scope的函数的返回值和外部scope的任何属性绑定起来
(1)@:单向绑定

示例代码:

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>
<!--内部隔离scope-->
<my-directive my-text="{{input}}"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>自定义指令scope:<input type="text" ng-model="myText"></p>',
            scope: {
                myText: '@'
            }
        }
    });
</script>
</body>

(2)=:双向绑定

示例代码:

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>

<!--内部隔离scope-->
<!--注意这里,因为是双向绑定,所以这里不要“{{}}”这个符号-->
<my-directive my-text="input"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>自定义指令scope:<input type="text" ng-model="myText"></p>',
            scope: {
                myText: '=' // 这里改成了双向绑定
            }
        }
    });
</script>
</body>
(3)&:内部scope的函数返回值和外部scope绑定

 

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>

<!--内部隔离scope-->
<!--注意这里,函数名字也要用 连字符命名法-->
<my-directive get-my-text="input"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>结果:{{ getMyText() }}</p>',
            scope: {
                getMyText: '&' // 这里改成了函数返回值的绑定
            }
        }
    });
</script>
</body>

bootstrap-datetimepicker文档

此地址可以克隆或fork本项目

git clone git://github.com/smalot/bootstrap-datetimepicker.git

希望这个小小的项目能帮到你 !

十年视图

1601281761-4178-standard-decade

年视图

1601281746-7193-standard-year

月视图

1601281751-4054-standard-month

日视图*

1601281746-2137-standard-day

小时视图 *

1601281746-5354-standard-hour

Day view w/ meridian *

1601281751-4898-standard-day-meridian

Hour view w/ meridian *

1601281753-5799-standard-hour-meridian

(*) Added views to select the time part.

需要bootstrap的下拉菜单组件 (dropdowns.less) 的某些样式,还有bootstrap的sprites (sprites.less and associated images) 中的箭头图标。

A standalone .css file (including necessary dropdown styles and alternative, text-based arrows) can be generated by running build/build_standalone.less through the lessc compiler:

$ lessc build/build_standalone.less datetimepicker.css

所有需要”Date” 的选项都可以处理Date 对象; a String formatted according to the given format; or a timedelta relative to today, eg ‘-1d’, ‘+6m +1y’, etc, where valid units are ‘d’ (day), ‘w’ (week), ‘m’ (month), and ‘y’ (year).

你也可以指定一个符合 ISO-8601 格式的日期时间,就可以忽略下面的格式:

  • yyyy-mm-dd
  • yyyy-mm-dd hh:ii
  • yyyy-mm-ddThh:ii
  • yyyy-mm-dd hh:ii:ss
  • yyyy-mm-ddThh:ii:ssZ

format

String. 默认值: ‘mm/dd/yyyy’

日期格式, p, P, h, hh, i, ii, s, ss, d, dd, m, mm, M, MM, yy, yyyy 的任意组合。

  • p : meridian in lower case (‘am’ or ‘pm’) – according to locale file
  • P : meridian in upper case (‘AM’ or ‘PM’) – according to locale file
  • s : seconds without leading zeros
  • ss : seconds, 2 digits with leading zeros
  • i : minutes without leading zeros
  • ii : minutes, 2 digits with leading zeros
  • h : hour without leading zeros – 24-hour format
  • hh : hour, 2 digits with leading zeros – 24-hour format
  • H : hour without leading zeros – 12-hour format
  • HH : hour, 2 digits with leading zeros – 12-hour format
  • d : day of the month without leading zeros
  • dd : day of the month, 2 digits with leading zeros
  • m : numeric representation of month without leading zeros
  • mm : numeric representation of the month, 2 digits with leading zeros
  • M : short textual representation of a month, three letters
  • MM : full textual representation of a month, such as January or March
  • yy : two digit representation of a year
  • yyyy : full numeric representation of a year, 4 digits

weekStart

Integer. 默认值:0

一周从哪一天开始。0(星期日)到6(星期六)

startDate

Date. 默认值:开始时间

The earliest date that may be selected; all earlier dates will be disabled.

endDate

Date. 默认值:结束时间

The latest date that may be selected; all later dates will be disabled.

daysOfWeekDisabled

String, Array. 默认值: ”, []

Days of the week that should be disabled. Values are 0 (Sunday) to 6 (Saturday). Multiple values should be comma-separated. Example: disable weekends: '0,6' or [0,6].

autoclose

Boolean. 默认值:false

当选择一个日期之后是否立即关闭此日期时间选择器。

startView

Number, String. 默认值:2, ‘month’

日期时间选择器打开之后首先显示的视图。 可接受的值:

  • 0 or ‘hour’ for the hour view
  • 1 or ‘day’ for the day view
  • 2 or ‘month’ for month view (the default)
  • 3 or ‘year’ for the 12-month overview
  • 4 or ‘decade’ for the 10-year overview. Useful for date-of-birth datetimepickers.

minView

Number, String. 默认值:0, ‘hour’

日期时间选择器所能够提供的最精确的时间选择视图。

maxView

Number, String. 默认值:4, ‘decade’

日期时间选择器最高能展示的选择范围视图。

todayBtn

Boolean, “linked”. 默认值: false

如果此值为true 或 “linked”,则在日期时间选择器组件的底部显示一个 “Today” 按钮用以选择当前日期。如果是true的话,”Today” 按钮仅仅将视图转到当天的日期,如果是”linked”,当天日期将会被选中。

todayHighlight

Boolean. 默认值: false

如果为true, 高亮当前日期。

keyboardNavigation

Boolean. 默认值: true

是否允许通过方向键改变日期。

language

String. 默认值: ‘en’

The two-letter code of the language to use for month and day names. These will also be used as the input’s value (and subsequently sent to the server in the case of form submissions). Currently ships with English (‘en’), German (‘de’), Brazilian (‘br’), and Spanish (‘es’) translations, but others can be added (see I18N below). If an unknown language code is given, English will be used.

forceParse

Boolean. 默认值: true

当选择器关闭的时候,是否强制解析输入框中的值。也就是说,当用户在输入框中输入了不正确的日期,选择器将会尽量解析输入的值,并将解析后的正确值按照给定的格式format设置到输入框中。

minuteStep

Number. 默认值: 5

此数值被当做步进值用于构建小时视图。对于每个 minuteStep 都会生成一组预设时间(分钟)用于选择。

pickerReferer : 不建议使用

String. 默认值: ‘default’ (other value available : ‘input’)

The referer element to place the picker for the component implementation. If you want to place the picker just under the input field, just specify input.

pickerPosition

String. 默认值: ‘bottom-right’ (还支持 : ‘bottom-left’)

此选项当前只在组件实现中提供支持。通过设置选项可以讲选择器放倒输入框下方。

viewSelect

Number or String. 默认值: same as minView (supported values are: ‘decade’, ‘year’, ‘month’, ‘day’, ‘hour’)

With this option you can select the view from which the date will be selected. By default it’s the last one, however you can choose the first one, so at each click the date will be updated.

showMeridian

Boolean. 默认值: false

This option will enable meridian views for day and hour views.

initialDate

Date or String. 默认值: new Date()

You can initialize the viewer with a date. By default it’s now, so you can specify yesterday or today at midnight …

组件模版。

<div class="input-append date" id="datetimepicker" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
    <input class="span2" size="16" type="text" value="12-02-2012">
    <span class="add-on"><i class="icon-th"></i></span>
</div>

带有重置按钮(用于清空输入框)的组件模版。

<div class="input-append date" id="datetimepicker" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
    <input class="span2" size="16" type="text" value="12-02-2012">
    <span class="add-on"><i class="icon-remove"></i></span>
    <span class="add-on"><i class="icon-th"></i></span>
</div>

.datetimepicker(options)

初始化日期时间选择器。

remove

参数: None

移除日期时间选择器。同时移除已经绑定的event、内部绑定的对象和HTML元素。

$('#datetimepicker').datetimepicker('remove');

show

参数: None

显示日期时间选择器。

$('#datetimepicker').datetimepicker('show');

hide

参数: None

隐藏日期时间选择器。

$('#datetimepicker').datetimepicker('hide');

update

参数: None

使用当前输入框中的值更新日期时间选择器。

$('#datetimepicker').datetimepicker('update');

setStartDate

参数:

  • startDate (String)

给日期时间选择器设置一个新的起始日期。

$('#datetimepicker').datetimepicker('setStartDate', '2012-01-01');

Omit startDate (or provide an otherwise falsey value) to unset the limit.

$('#datetimepicker').datetimepicker('setStartDate');
$('#datetimepicker').datetimepicker('setStartDate', null);

setEndDate

参数:

  • endDate (String)

给日期时间选择器设置结束日期。

$('#datetimepicker').datetimepicker('setEndDate', '2012-01-01');

Omit endDate (or provide an otherwise falsey value) to unset the limit.

$('#datetimepicker').datetimepicker('setEndDate');
$('#datetimepicker').datetimepicker('setEndDate', null);

setDaysOfWeekDisabled

参数:

  • daysOfWeekDisabled (String|Array)

Sets the days of week that should be disabled.

$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled', [0,6]);

Omit daysOfWeekDisabled (or provide an otherwise falsey value) to unset the disabled days.

$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled');
$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled', null);

Datetimepicker 类暴露了一组event用以对日期进行操作。

show

当选择器显示时被触发。

hide

当选择器隐藏时被触发。

changeDate

当日期被改变时被触发。

$('#date-end')
.datetimepicker()
.on('changeDate', function(ev){
    if (ev.date.valueOf() < date-start-display.valueOf()){
        ....
    }
});

changeYear

当十年视图上的年视图view被改变时触发。

changeMonth

当年视图上的月视图view被改变时触发。

outOfRange

当用户选择的日期超出startDate 或endDate 时,或者通过setDate 或 setUTCDate方法设置日期超出范围时被触发。

日期时间选择器提供了键盘导航:

up, down, left, right 方向键

这些方向键中,left/right 向后/向前 一天,up/down 向后/向前 一周。

配合shift键,up/left 向后退一个月,down/right 向前进一个月。

配置ctrl键,up/left 向后退一年,down/right 向前进一年。

Shift+ctrl 和 ctrl 同等效果 – 也就是说,他们不能同时改变月和年,只能单独改变年。

escape

escape 键可以用来隐藏、重新显示日期时间选择器;当用户希望手工编辑输入框中的值是会很有用。

enter

当选择器处于显示状态时,enter键只是将其隐藏。当选择器处于隐藏状态时,enter键发挥通常的功能 – 提交当前表单,或者其他。

本插件支持月、每周中天的名称、weekStart选项的国际化。默认是语言是English (‘en’);其它可以使用的翻译文件在js/locales/ 目录中,只需在本插件之后引入需要的语言文件即可。需要增加额外语言支持的话,只需向 $.fn.datetimepicker.dates中增加一个key即可,一定要放在调用 .datetimepicker()之前。如下案例:

$.fn.datetimepicker.dates['en'] = {
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    today: "Today"
};

Right-to-left languages may also include rtl: true to make the calendar display appropriately.

If your browser (or those of your users) is displaying characters wrong, chances are the browser is loading the javascript file with a non-unicode encoding. Simply add charset="UTF-8" to your script tag:

<script type="text/javascript" src="bootstrap-datetimepicker.de.js" charset="UTF-8"></script>

绑定输入框,并设置format选项:

<input type="text" value="2012-05-15 21:05" id="datetimepicker">
$('#datetimepicker').datetimepicker({
    format: 'yyyy-mm-dd hh:ii'
});

绑定输入框,并设置format标记:

<input type="text" value="2012-05-15 21:05" id="datetimepicker" data-date-format="yyyy-mm-dd hh:ii">
$('#datetimepicker').datetimepicker();

作为组件使用:

<div class="input-append date" id="datetimepicker" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
    <input size="16" type="text" value="12-02-2012" readonly>
    <span class="add-on"><i class="icon-th"></i></span>
</div>
$('#datetimepicker').datetimepicker();

作为内联日期时间选择器:

<div id="datetimepicker"></div>
$('#datetimepicker').datetimepicker();
1239
 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |