目录
目录
文章目录
  1. ##CSS似酒,得品;JS似剑,得磨。
  2. 重剑无锋,大巧不工,路漫漫其修远兮,上下而求索吧,少年。

前端九剑

##CSS似酒,得品;JS似剑,得磨。

重剑无锋,大巧不工,路漫漫其修远兮,上下而求索吧,少年。

  • 第一式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var obj = {
array: [1, 2, 3],
sum: ()=> {
console.log(this === window); // => true
return this.array.reduce((result, item) => result + item);
}
};
obj.sum(); // => Uncaught TypeError: Cannot read property 'reduce' of undefined(…)
出现错误,无法读出没有定义的‘reduce’属性。原因是箭头函数没有它自己的this值,其内部的this值继承自外围作用域。
那么修改代码:
var obj = {
array: [1, 2, 3],
sum: function() {
console.log(this === window); // => false
return this.array.reduce(function(result, item) {
reutrn result + item;
});
}
};
obj.sum(); // 6
  • 第二式
1
2
3
4
5
6
7
8
var multiply = (a, b) => {
return b === undefined ? (b) => { return a * b } : a * b;
};
var double = multiplys(2);
double(3); // => 6
multiply(2, 3); // => 6
  • 第三式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
*
* @param str {string}
* @param expectsLowerCase {boolean}
*
* @return {function}
*/
function markup(str, expectsLowerCase) {
var map = object.create(null);
var list = str.split(',');
for(var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
console.log(map);
return expectsLowerCase
? function(val) { return map[val.toLowerCase()] ? true : false; }
: function(val) { return map[val] ? true : false; }
}
var str = 'hello world,i love you.';
var fn = markup(str, false); // => Object {hello world: true, i love you.: true}
console.log(fn('hello')); // false
console.log(fn('hello world')); // true
  • 第四式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 函数节流
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function(){
method.call(context);
}, 100);
}
// 全屏元素
funtion fullScreen(element,h,w) {
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
if(h) {
element.style.height = screenHeight + 'px';
}
if(w) {
element.style.width = screenWidth + 'px';
}
}
// 窗口调整事件
window.onresize = funtion() {
throttle(fullScreen(document.querySelector(''),true,true));
};
// 相关技术:移动端适配
  • 第五式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var easingMap = {
"linear": [0.250, 0.250, 0.750, 0.750],
"ease": [0.250, 0.100, 0.250, 1.000],
"easeIn": [0.420, 0.000, 1.000, 1.000],
"easeOut": [0.000, 0.000, 0.580, 1.000],
"easeInOut": [0.420, 0.000, 0.580, 1.000],
"easeInQuad": [0.550, 0.085, 0.680, 0.530],
"easeInCubic": [0.550, 0.055, 0.675, 0.190],
"easeInQuart": [0.895, 0.030, 0.685, 0.220],
"easeInQuint": [0.755, 0.050, 0.855, 0.060],
"easeInSine": [0.470, 0.000, 0.745, 0.715],
"easeInExpo": [0.950, 0.050, 0.795, 0.035],
"easeInCirc": [0.600, 0.040, 0.980, 0.335],
"easeInBack": [0.600, -0.280, 0.735, 0.045],
"easeOutQuad": [0.250, 0.460, 0.450, 0.940],
"easeOutCubic": [0.215, 0.610, 0.355, 1.000],
"easeOutQuart": [0.165, 0.840, 0.440, 1.000],
"easeOutQuint": [0.230, 1.000, 0.320, 1.000],
"easeOutSine": [0.390, 0.575, 0.565, 1.000],
"easeOutExpo": [0.190, 1.000, 0.220, 1.000],
"easeOutCirc": [0.075, 0.820, 0.165, 1.000],
"easeOutBack": [0.175, 0.885, 0.320, 1.275],
"easeInOutQuad": [0.455, 0.030, 0.515, 0.955],
"easeInOutCubic": [0.645, 0.045, 0.355, 1.000],
"easeInOutQuart": [0.770, 0.000, 0.175, 1.000],
"easeInOutQuint": [0.860, 0.000, 0.070, 1.000],
"easeInOutSine": [0.445, 0.050, 0.550, 0.950],
"easeInOutExpo": [1.000, 0.000, 0.000, 1.000],
"easeInOutCirc": [0.785, 0.135, 0.150, 0.860],
"easeInOutBack": [0.680, -0.550, 0.265, 1.550],
"custom": [0.000, 0.350, 0.500, 1.300],
"random": [
Math.random().toFixed(3),
Math.random().toFixed(3),
Math.random().toFixed(3),
Math.random().toFixed(3)
]
}
  • 第六式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 页面垂直向下滚动指定距离的缓动函数
// num:指定滚动的距离, boolean:true(垂直),false(水平)
// time: 缓动时间, oncomplete:回调函数
function scrollThere(num, boolean, time, oncomplete) {
time = time || 500;
num = num || 0;
var ease = Math.sqrt;
var start = (new Date()).getTime();
animate();
function animate() {
var elapsed = (new Date()).getTime() - start;
var fraction = elapsed / time;
if(boolean) {
if(fraction < 1) {
var A = ease(fraction);
var C = ease(num);
window.scrollBy(0, C*A);
setTimeout(animate, Math.min(25, time - elapsed));
} else {
window.scrollBy(0, num);
if(oncomplete) oncomplete();
}
} else {
if(fraction < 1) {
var B = ease(fraction);
var D = ease(num);
window.scrollBy(D*B, 0);
setTimeout(animate, Math.min(25, time - elapsed));
} else {
window.scrollBy(num, 0);
if(oncomplete) oncomplete();
}
}
}
}
// 相关技术:页面垂直滚动
  • 第七式
1
2
3
4
5
6
7
8
9
// 获取格式化时间
var _getTime = function() {
var _ = ['01','02','03','04','05','06','07','08','09'], // 补零
d = new Date(),
h = d.getHours(),
m = d.getMinutes(),
s = d.getSeconds();
return [ _[h]||h, _[m]||m, _[s]||s ].join(':');
}
  • 第八式
1
2
3
4
5
6
7
8
9
10
11
// navigator 代码检测应用
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1;
console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
  • 第九式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 浏览器的事件处理兼容处理
var EventUtil = {
// 添加事件处理
addEventer: function(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent('on' + type, handler);
} else {
element['on' + type] = handler;
}
},
// 移除事件处理
removeEventer: function(element, type, hanlder) {
if(element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if(element.detachEvent) {
element.detachEvent('on' + type, handler);
} else {
element['on' + type] = null;
}
}
};
  • 第十式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// JS原生宽、高度
// 窗口大小(IE9+)
window.innerHeight(当前可视页面的大小)
window.innerWidth
window.outerHeight
window.outerWidth
resizeTo()
resizeBy()
// 窗口位置
screenLeft
screenTop
screenX(opera)
screenY(opera)
moveTo()
moveBy()
// 屏幕信息
screen.height(屏幕的高度,跟电脑本身相关)
screen.width(屏幕的宽度)
screen.avilHeight
screen.avilWidth
// body元素的client(可视部分宽度和高度,padding+content)
document.body.clientHeight(当然,body可改成页面中其他任何元素)
document.body.clientWidth
document.body.clientTop
document.body.clientLeft
// body元素的offset(border+padding+content)
document.body.offsetWidth
document.body.offsetHeight
document.body.offsetLeft
document.body.offsetTop
// body元素的scroll
document.body.scrollWidth
document.body.scrollHeight
document.body.scrollTop
document.body.scrollLeft
scrollTo()
scrollBy()
// 综合比较 document.body
clientHeight
大家对 clientHeight 都没有什么异议,都认为是内容可视区域的高度
offsetHeight
IE、Opera 认为 offsetHeight = clientHeight + 滚动条 + 边框。 NS、FF 认为 offsetHeight 是网页内容实际高度,可以小于 clientHeight。
scrollHeight
IE、Opera 认为 scrollHeight 是网页内容实际高度,可以小于 clientHeight。 NS、FF 认为 scrollHeight 是网页内容高度,不过最小值是 clientHeight
// 获取浏览器窗口(视口)innerWidth和innerHeight的兼容性写法
function getInnerWH() {
var pageWidth = window.innerWidth;
var pageHeight = window.innerHeight;
if(typeof pageWidth != 'number') {
if(document.compatMode == 'CSS1Compat') {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
return [pageWidth, pageHeight];
}
function scrollBottomOrTop() {
var viewportHeight = getInnerWH()[1];
var scrollTop = document.body.scrollTop;
var wholeHeight = document.body.scrollHeight;
if(viewportHeight + scrollTop >= wholeHeight) {
alert('bottom');
}
if(scrollTop == 0) {
alert('top');
}
}
window.onscroll = scrollBottomOrTop;
// 相关技术:可视区加载,延迟加载(懒加载)

图示

  • 第十一式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    // 触屏事件
    function loadTouchEvent (){
    document.addEventListener('touchstart',touch,false);
    document.addEventListener('touchmove',touch,false);
    document.addEventListener('touchend',touch,false);
    function touch (event){
    event = event || window.event;
    var oInp = document.getElementById("inp");
    switch(event.type){
    case "touchstart":
    oInp.innerHTML ="Touch started (" + event.touches[0].clientX +"," + event.touches[0].clientY +")";
    break;
    case "touchend":
    oInp.innerHTML ="<br>Touch end (" + event.changedTouches[0].clientX +"," + event.changedTouches[0].clientY +")";
    break;
    case "touchmove":
    event.preventDefault();
    oInp.innerHTML ="<br>Touch moved (" + event.touches[0].clientX +"," + event.touches[0].clientY +")";
    break;
    }
    }
    }
    window.addEventListener('load',loadTouchEvent,false);
  • 第十二式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 封装CSS类的操作
    H5为每个元素定义了classList属性,该属性值是DOMTokenList对象,一个类数组对象。
    这个对象还定义了如下的方法:
    1、add(value),将给定的字符串值添加到class列表中,如果存在,则忽略。
    2、containes(value),表示class列表中是否存在给定的值,如果存在则返回true,否则返回false。
    3、remove(value),从class列表中删除给定的字符串。
    4、toggle(value),如果列表中已经存在给定的值,删除它;如果列表中没有给定的值,添加它。
    但是,IE8不支持classList属性,IE9+部分支持,简直毒瘤。
    // 兼容写法

    classList的兼容情况

  • 第十三式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // 获取元素的指定样式,getComputedStyle(element,null)在IE8或更早的版本没有实现,只能使用currentStyle属性。
    /* * *
    * 获取元素的指定样式
    * @param obj element
    * @param attr string
    * @returns {*} string
    */
    function getStyle(obj,attr) {
    // IE
    if(obj.currentStyle) {
    return obj.currentStyle[attr];
    } else {
    return getComputedStyle(obj,null)[attr];
    }
    }
  • 第十四式

    1