2013年8月

零CSS3筆記 | html5

placeholder 自定義樣式

/* 通用 */
::-webkit-input-placeholder { color:#f00; }
::-moz-placeholder { color:#f00; } /* firefox 19+ */
:-ms-input-placeholder { color:#f00; } /* ie */
input:-moz-placeholder { color:#f00; }

/* webkit专用 */
#field2::-webkit-input-placeholder { color:#00f; }
#field3::-webkit-input-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }
#field4::-webkit-input-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; }

/* mozilla专用 */
#field2::-moz-placeholder { color:#00f; }
#field3::-moz-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }
#field4::-moz-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; }

零CSS3筆記 | UI

圆角
border-radius:左上 右上 右下 左下
border-radius: x軸/y軸
border-radius: 10px 20px 30px 40px / 10px 30px 40px 80px;

<pre>.box-p{width: 90px;transition: 2s linear;}
.box{width: 40px;height: 40px;background:green;display:inline-block}
.box:nth-of-type(1){border-radius: 0 50%}
.box:nth-of-type(2){border-radius: 50% 0 }
.box:nth-of-type(3){border-radius: 50% 0}
.box:nth-of-type(4){border-radius: 0 50%}
.box-p:hover{-webkit-transform:rotate(360deg)}
</pre>

See the Pen KdKPEQ by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


邊框圖片border-image:url 四邊切割大小 排列方式

border-image-sourceg 引入图片

border-image-slice 切割图片

border-image-width 边框宽度

border-image-repeat 图片的排列方式

边框颜色 border-colors

<pre>.box{width: 100px;height: 100px;
border-image:url('http://elmok.com/img/border-img.jpg';) 27 27 27 27 round round;
/27表示切割被引用圖片四邊的距離,類似於padding/
/以下中間部填充只有webkit實現/
-webkit-border-image:url('http://elmok.com/img/border-img.jpg';) 27 27 27 27 round round;
border-width:20px;
}
.box2{width: 100px;height: 100px;
border:10px solid #166994;
-moz-border-left-colors:saddlebrown yellow ;
}
</pre>

See the Pen avborx by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


線性漸變
线性渐变格式:linear-gradient([<起点> || <角度>,]? <点>, <点>…)

重覆平鋪:repeating-linear-gradient

加入点的位置

top, red 40%, green 60%

top, red 50%, green 50%

同一个位置两个点——直接跳变

也可以用px

配合rgba

top, rgba(255,255,255,1), rgba(255,255,255,0)

加入背景图片

background: -webkit-linear-gradient (top, rgba(255,255,255,1) 30%, rgba(255,255,255,0)), url(a.gif)

/*写法一:注意标点*/
background-image:-webkit-linear-gradient(left top,red blue)
/*写法二:*/
background-image:-webkit-linear-gradient(30deg,red,blue,yellow...)
/*写法三:*/
background-image:-webkit-linear-gradient(top,red 0,blue 100%);
/*写法四:重复平铺*/
background-image:-webkit-repeating-linear-gradient(top,red 0,blue 30px);
/*条纹背景:*/
background: -webkit-repeating-linear-gradient(left,green 0,green 10px,#ffffff 10px,#fff 20px);
/*簡單寫*/
.box{ width: 200px; height: 200px;
     background: -webkit-linear-gradient(red,blue);
     background: -moz-linear-gradient(red,blue);
     background: -o-linear-gradient(red,blue);
     background: -ms-linear-gradient(red,blue);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='red',endColorstr='blue',GradientType='0'); /* 1,左-右 0 上-下 */
    }

<pre>.box{width: 300px;height: 40px;text-align: center;color: #fff;line-height: 40px;
/定義光暈/
background:
-webkit-linear-gradient(-45deg,
rgba(255,255,255,0) 0,
rgba(255,255,255,0.4) 155px,
rgba(255,255,255,0.9) 158px,
rgba(255,255,255,0.5) 160px,
rgba(255,255,255,0) 170px)
no-repeat -300px,
#000;
transition: 2s
}
/ 两个背景,gradient及url背景 /
.box:hover{background-position: 300px 0,0 0 ;}
</pre>

See the Pen vNYBoL by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


径向渐变:radial-gradient([<起点>]? [<形状> || <大小>,]? <点>, <点>…);

radial-gradient([<起点>]? [<形状> || <大小>,]? <点>, <点>…);

起点:可以是关键字(left,top,right,bottom),具体数值或百分比

形状: ellipse、circle

大小 :具体数值或百分比,也可以是关键字(最近端,最近角,最远端,最远角,包含或覆盖 (closest-side, closest-corner, farthest-side, farthest-corner, contain or cover));

注意firefox目前只支持关键字

<pre>.box{width:200px;height:200px;border:1px solid #000;float:left;margin:10px}
.box:nth-of-type(1){background:-webkit-radial-gradient(100px 50px,closest-side,#fff ,#000)}
.box:nth-of-type(2){background:-webkit-radial-gradient(100px 50px,closest-corner,#fff ,#000)}
.box:nth-of-type(3){background:-webkit-radial-gradient(100px 50px,farthest-side,#fff ,#000)}
.box:nth-of-type(4){background:-webkit-radial-gradient(100px 50px,farthest-corner,#fff ,#000)}
.box:nth-of-type(5){background:-webkit-radial-gradient(100px 50px,contain,#fff ,#000)}
.box:nth-of-type(6){background:-webkit-radial-gradient(100px 50px,cover,#fff ,#000)}
</pre>

See the Pen LpYYEY by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


多背景,逗號分開:background: url(a.jpg) 0 0, url(b.jpg) 0 100%;

背景尺寸: background-size:x y

background-size:100% 100%

Cover 放大

Contain 缩小

<pre>.box{width: 400px;height: 100px;border:10px solid #000;
background:
url('http://elmok.com/img/bgcov1.png';) no-repeat,
url('http://elmok.com/img/bgcov2.png';) no-repeat 0 bottom
}
.box2,.box3,.box4{margin-top: 10px;width: 400px;height: 50px;border:10px solid #000;
background:url('http://elmok.com/img/bgcov1.png';) no-repeat;}
.box2{background-size:100% 100%}
.box3{background-size:cover}
.box4{background-size:contain}
</pre>

See the Pen BoaaNd by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


background-origin : border | padding | content

從下面的值開始顯示完整圖片,但無論border,還是padding都會顯示背景,所以需要background-clip;

border-box: 从border区域开始显示背景。

padding-box: 从padding区域开始显示背景。

content-box: 从content区域开始显示背景。

background-clip

border: 从border区域向外裁剪背景。

padding: 从padding区域向外裁剪背景。

content: 从content区域向外裁剪背景。

no-clip: 从border区域向外裁剪背景。

配合:-webkit-background-clip:text; background-position,可做出webkit獨有效果

<pre>.box{width: 300px;height: 300px;display:inline-block;
background:url('http://elmok.com/img/h5.jpg';);
border:30px solid rgba(0,0,0,.7);
background-origin: padding-box;
background-clip:padding-box
}

.box1{width: 300px;height: 300px;display:inline-block;
background:url('http://elmok.com/img/h5.jpg';);
/webkit獨有/
font: bold 80px/100px '微软雅黑'; text-align: center; color: rgba(0,0,0,0);
-webkit-background-clip:text;
}
.box1:hover{
background-position: -300px -300px;}
</pre>

See the Pen meddrR by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
1)先做光暈,background:background: -webkit-linear-gradient(-30deg,rgba(255,255,255,0) 100px,rgba(255,255,255,1) 150px,rgba(255,255,255,1) 150px,rgba(255,255,255,1) 200px,rgba(255,255,255,1) 240px,rgba(255,255,255,0) 300px) no-repeat -300px 0;

2)利用webkit支持-webkit-background-clip: text;/ 只有文字有背景/

3)使用background-position 滑動;
<pre>body{background:#000;text-align:center;font-size:50px;line-height:200px}
h1{background:-webkit-linear-gradient(-30deg,rgba(255,255,255,0) 100px,rgba(255,255,255,1) 150px,rgba(255,255,255,1) 150px,rgba(255,255,255,1) 200px,rgba(255,255,255,1) 240px,rgba(255,255,255,0) 300px) no-repeat -300px 0;color:rgba(255,255,255,.5);-webkit-background-clip:text}
h1:hover{background-position:1000px 0}
</pre>

See the Pen jbOOVp by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


遮罩,也只有webkit實現

Mask-image

Mask-position

Mask-repeat

实例:特殊形状的幻灯片效果
<pre>.box{width: 600px;height: 300px;background:url('http://elmok.com/img/h1.jpg';);border:1px solid #000;
-webkit-mask: url('http://elmok.com/img/mask.png';) no-repeat center;
transition:1s;
}
.box:hover{-webkit-mask-position: 100% 50%}
</pre>

See the Pen WQNNpJ by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

零CSS3筆記 | @media

@media 设备名 only (选取条件) not (选取条件) and(设备选取条件),设备二{sRules}

max-width:800px 最大寬度為800px 即800px以下生效

min-width:800px 最小寬度為800px 即800px以上生效

(min-width:400px) and (max-width:800px) 400-800之間

min-width时,小的放上面大的在下面,同理如果是用max-width那么就是大的在上面,小的在下面

<link rel="stylesheet" href="css3-2.css" media="screen and (min-width:400px) and (max-width:800px)"/>

@media screen and (min-width: 600px) and (max-width: 900px){
    something....
}

@media all and (orientation:portrait){ /*豎屏,即高>寬*/
    something....
}

@media all and (orientation:landscape){ /*橫屏,即高<寬*/
    something....
}

@media all and (orientation:landscape){ /*橫屏,即高<寬*/
    something....
}
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0" />
/*大致初始化*/
/* 禁用iPhone中Safari的字号自动调整 */
html {
    -webkit-text-size-adjust: none;
}
/* 设置HTML5元素为块 */
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
    display: block;
}
/* 设置图片视频等自适应调整 */
img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}
.video embed, .video object, .video iframe {
    width: 100%;
    height: auto;
}
@media (device-height:568px) and (-webkit-min-device-pixel-ratio:2){/* 兼容iphone5 */}
@media only screen and (max-device-width :480px){ }
@media only screen and (min-device-width :481px){ }

/*6*/
@media (min-device-width : 375px) and (max-device-width : 667px) and (-webkit-min-device-pixel-ratio : 2){ }

/*6+*/
@media (min-device-width : 414px) and (max-device-width : 736px) and (-webkit-min-device-pixel-ratio : 3){ }

/*魅族*/
@media only screen and (min-device-width :1080px) and (-webkit-min-device-pixel-ratio : 2.5){ }

/*mate7*/
@media only screen and (min-device-width :1080px) and (-webkit-min-device-pixel-ratio : 3){ }

/*4 4s*/
@media only screen and (device-height :480px) and (-webkit-device-pixel-ratio:2){ }

零JS筆記 | 定時器 | 抖動

setInterval(函數,毫秒);
clearInteval( setInterval(函數,毫秒); )
注意理解: num %= arr.length;

See the Pen vNBmeE by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

圖片切換實例更改
<a href='http://www.elmok.com/js/%E6%9C%80%E7%B0%A1%E5%96%AE%E7%9A%84%E5%9C%96%E7%89%87%E5%88%87%E6%8F%9B%E4%BA%8C.html
' target='_blank'>最簡單的圖片自動切換

function aplay(){
var timer = setInterval(function(){
    num++;
    num %= arrimg.length;//num = 0 1 2 3 4  === if(num = lis.length){num = 0}
    tab()
},1000)
}
//去掉鼠標移入移出
box.onmouseover = function(){
    clearInterval(timer)
};
box.onmouseout = aplay  //不能加括號

//打開時隔2s後再執行;體驗 
setTimeout(aplay,2000)

應用:打開網頁自動彈出;
setTimerout(函數,毫秒);
clearTimeout( setTimerout(函數,毫秒); )

var imgbox = document.getElementById('img')
setTimeout(function(){
    imgbox.style.display = 'inline-block';    //圖片為 inline-block;
        setTimeout(function(){                //3秒後關閉; 
            imgbox.style.display = 'none'
        },3000)
},2000)

圖片鼠標按下自動滾動,抬起停止
onmousedown
onmouseup

See the Pen PPYmMj by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

抖動函數
原理:原位置以遞減方式向兩邊相加,越加越小直到0;
抖完後執行回調~

//方法封裝
function shake(obj, attr, pos, endfn) {
  // var pos = parseInt(getStyle(obj,attr)); //去掉ps //隱患,多次觸發時每次的初始位置不同;
  var arr = []; //20 -20 18 -18
  var shake = null;
  var num = 0;
  for (var i = 20; i > 0; i -= 2) {
    arr.push(i, - i);
  }
  arr.push(0);
  clearTimeout(obj.shake)
  shake = setInterval(function () {
    obj.style[attr] = pos + arr[num] + 'px'
    num++
    if (num == arr.length) {
      clearInterval(obj.shake)
      endfn && endfn()
    }
  }, 50)
}
var img = document.getElementsByTagName('img')
var on = true;
for (var i = 0; i < img.length; i++) {
  img[i].style.left = 100 + i * 110 + 'px'
  var pos = parseInt(getStyle(img[i], 'top'));
  img[i].onmousemove = function () {
    shake(this, 'top', pos)
  }
}
<img src="c1.jpg" alt="" width="150"/>
<img src="c2.jpg" alt="" width="150"/>
<img src="c3.jpg" alt="" width="150"/>
<img src="c4.jpg" alt="" width="150"/>
<img src="c5.jpg" alt="" width="150"/>

修復版:

    function shake(obj, attr, endfn) {
        if (obj.door) {
            return
        }
        obj.door = 1;
        var pos = parseInt(css(obj,attr)); 
        var arr = []; //20 -20 18 -18
        var num = 0;
        for (var i = 20; i > 0; i -= 2) {
            arr.push(i, - i);
        }
        arr.push(0);
        clearTimeout(obj.shake)
        obj.shake = setInterval(function () {
            obj.style[attr] = pos + arr[num] + 'px'
            num++
            if (num == arr.length) {
                clearInterval(obj.shake)
                endfn && endfn()
                obj.door = 0;
            }
        }, 50)
    }

零JS筆記 | 運算符 | 流程控制 | return | getStyle

0%3 = 0
1%3 = 1
2%3 = 2
3%3 = 0

a%b
a未遇到自己前,=a
a遇到自己, =0
a超過自己,=除以整數倍a後,又開始未遇到自己的情況

var i = 0;
i++;
if (i === 5) {
  i = 0
} //可寫成下面

i % 5 //i = 0 1 2 3 4
for(var i=0;i<a;i++){
    i%b
}
if( a<=b ){ 0.1.2.3...a-1 }
if( a>b  ){ 0.1.2.3...b-1...[0.1.2....a-b-1 ]}

var s  =6500 //秒
alert(Math.floor(s/60)+'分'+s%60+'秒')

給所有li加間隔顏色,及移入移出

var ul = document.getElementById('ul')
var li = ul.getElementsByTagName('li')
var arr = ['red','yellow','blue'];

//第一種寫法
for (var i = 0; i < li.length; i++) {
  li[i].index = i;
  li[i].style.background = arr[i % arr.length]; //0 1 2 0 1 2 0 1 2 .....
  li[i].onmousemove = function () {
    this.style.background = 'gray'
  }
  li[i].onmouseout = function () { //for 裏包fn,不能用i,所以給所有li建索引值
    this.style.background = arr[this.index % arr.length] // 0 1 2 0 1 2
  }
}

//第二種寫法
var str = '' //存鼠標移過去時原來的顏色
for (var i = 0; i < li.length; i++) {
  li[i].style.background = arr[i % arr.length];
  li[i].onmouseover = function () {
    str = this.style.background; // 先存颜色
    this.style.background = 'gray';
  };
  li[i].onmouseout = function () {
    this.style.background = str;
  };
}

重點思路:

1、同一li切換:使用開關on;
2、多個li切換:點擊時,先for清空所有li[i],再當前添加li[this.index]添加事件;

如:

var on = true;
for (var i = 0; i < li.length; i++) {
  li[i].index = i;
  li[i].style.background = arr[i % arr.length];
  li[i].onmouseover = function () {
    str = this.style.background; // 先存颜色
    this.style.background = 'gray';
  };
  li[i].onmouseout = function () {
    this.style.background = str;
  };
  li[i].onclick = function () {  //1、每次點擊時當前變黑色,先還原所有顏色,再當前添加黑色
    for (var i = 0; i < li.length; i++) {
      li[i].style.background = arr[i % arr.length];
    }
    this.style.background = '#000'
    for (var i = 0; i < li.length; i++) { //2、每次點擊時當前over/out事件去除,所以是先for還原所有事件,再當前去除事件 li[this.index]
      li[i].onmouseover = function () {
        str = this.style.background; // 先存颜色
        this.style.background = 'gray';
      };
      li[i].onmouseout = function () {
        this.style.background = str;
      };
    }
    li[this.index].onmouseover = li[this.index].onmouseout = null;
  }
}

&&與 、||或、!或
10 < 80 && 23 < 100 ,左邊必須成立才會看右邊

var a = 100>30 && 40
alert(a) //40
var a = 100<30 && 40
alert(a) //false

10 < 80 || 23 < 100 ,左邊成立,則不會看右邊;都不成立返回false

var a = 100>30 || 40
alert(a) // true
var a = 100<30 || 40
alert(a) // 40
var str = ''
alert(!!str) //false,//雙否表示:第一個先轉數據為boolean值,再取反;

反選小例子

var inp = document.getElementsByTagName('input')
inp[0].onclick = function () {
  for (var i = 1; i < inp.length; i++) {
    inp[i].checked = !inp[i].checked
  }
}

流程控制:
判斷:if switch (case break default) ?:
循環: while for
跳出:break continue

var str = 'js'
switch( str ){
    case 'js': alert('js');break;
    case 'html': alert('html');break;
    default: alert(str);
}
//break不加,則執行完後會繼續執行,直到遇見break或執行完所有
if(a<10){alert(a)}else{{alert(b)}}

a<b ? alert(a) : alert(b);
var i = 0;
while(i<3){
alert(i);
i++;
}

for(var i=0;i<6;i++){
    if(i==4){
        break; //跳出for,停止執行
    }
    alert(i)   // 0 1 2 3 
}   
//最後循環外的i = 4

for(var i=0;i<6;i++){
    if(i==4){
        continue ; //跳過這一次循環for
    }
    alert(i)  //0 1 2 3 5 
}
//最後循環外的i = 6


真假:數據類型-數字(NaN)、字符串、布爾、函數、對象{elem、[]、{}、null}、undefined

真:非0數字(正負數、小數)、非空字符串、true、函數、能找到的元素、[]、{}、
假:0、NaN、空字符串('')、false、不能找到的元素、null、undefined


return返回值

函數名() = return後面的內容

//return 函數
fn2()
function fn2(){
    return function(){
    alert(1)
}
}
fn2()() //彈出1

//return 對象
fn3().onload = function(){document.body.innerHTML = 123};function fn3(){return window}

//例如
function $(id) {
  return document.getElementById(id)
}

//簡單模擬$
function $(v) {
  if (typeof v === 'function') {
    window.onload = v;
  } 
  else if (typeof v === 'string') {
    return document.getElementById(v)
  } 
  else if (typeof v === 'object') {
    return v;
  }
}
$(function(){
    $('btn').onclick = ....
        $(this)....
})

alert(fn());
function fn(){
    return; //默認返回值為undefined;
}

function fn(){
    return 123;
        alert('無法彈出')
}
/*
1、函數名() = return 後面的值;
2、所有函數默認返回值:未定義;
3、return後任何代碼都不執行;
*/

函數內部: function fn(){ this return arguments event ...}
實參: fn(1,2,3)
形參: arguments ----- [實參的集合],無數組的方法
當函數參數個數無法確定時,使用arguments

fn(1,2,3)
function fn(){
    alert(arguments)  //object arguments
    alert(arguments.length)  //3
    alert(arguments[0]) //1
}
//小應用:當函數參數個數無法確定時,使用arguments
sum(1,2,3....'+')
function sum() {
  var n = 0;
  for (var i = 0; i < arguments.length - 1; i++) {
    if (arguments[arguments.length - 1] == '+') {
      n += arguments[i]
      alert(1)
    } 
    else if (arguments[arguments.length - 1] == '-') {
      n -= arguments[i]
    }
  }
  return n
}
//arguments 能讀也能寫,實參的集合
var a = 1;
function fn2(a){
    arguments[0] = 3 //arguments[0] = a
    alert(a);  //3
    var a =2
    alert(arguments[0])
}
fn2(a); //2
alert(a)  //1


獲取瀏覽器最終計算後樣式 :
1、getComputedStyle(obj).width IE9+
2、obj.currentStyle.width IE8-
注意:適用範圍 width height opacity backgroundColor zIndex marginRight ...只要有空格,全部undefined
另:不要去獲取未設置後的樣式 ;
FF4.0以前 getComputedStyle($('div'),4.0以前可以跟任何參數才有反應).width);


function getStyle(obj, attr) {
  return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj) [attr]
}

零JS筆記 | 作用域

瀏覽器:
JS解析器,在域內,一定會有兩步
1)找東西: var function 參數
2)逐行解讀代碼 [碰到script,及fn,會解析執行]

什麼是域: script 全局變量、全局函數

alert(a);
var a = 1;
function fn(){ alert(a) }

//1)找東西 找var function 參數
    a = undefined  //如果var去掉,則js解析器為空,所以a is not defined
    fn = function fn(){ alert(a) } (在倉庫內存放)
//2)逐行解讀代碼
    alert(a); 倉庫內為未定義
    var a = 1 ; (看見表達式:= + - * / % ++ -- 參數;)(把倉庫內的a = undefined 改為 a = 1) 
alert(a); //function a() { alert(4) 
var a = 1;
alert(a); //1
function a() { alert(2) ;}
alert(a); //1
var a = 3; //
alert(a); //3
function a() { alert(4) } 
alert(a); //3


//1)找東西 找var function 參數
  //a = undefined
    a = function a() { alert(2) } //又找到a,是函數,變量與函數重命,則只留函數
  //a = undefined                 //重命,只留下函數
    a = function a() { alert(4) } //遇到函數,前面被覆蓋;(存到倉庫裏只有這一行)
//2)逐行解讀代碼
    alert(a); //倉庫裏有 a = function a() { alert(4) } 
    var a = 1; //出現表達式,a被修改為 a = 1;
    function a() { alert(2) ;}  //函數聲明,不是表達式,所以不改東西 a = 1
    alert(a);  //所以1
    var a = 3     //出現表達式,a被修改為 a = 3;
    alert(a);  //所以是a = 3
    function a() { alert(4) }  ////函數聲明,不是表達式,所以不改東西 a= 3
    alert(a) //a = 3 //倉庫裏無函數了,所以若:
    a() //相當於 3(),報錯!
//域是分開執行的 先後順序,自上而下
<script> alert(a) </script>      // a is not defined 
<script> var a = 1 </script>
var a = 1;
function fn(){
    alert(a);
    var a = 2;
}
fn();
alert(a);

//1)找東西 找var function 參數
    a = undefined
    fn = function fn() { alert(a);var a = 2; }                 
//2)逐行解讀代碼
    a = 1;
    fn(); //1
           //1)找東西 找var function 參數  
               var a = 2  //a = undefined; // a为局部變量 ,與外面的a無關係 所以只在局部倉庫裏;
           //2)逐行解讀代碼
                a = 2;    //局部垃圾回收機制回收
    alert(a) //1 全局倉庫裏
var a = 1;
function fn(){
    alert(a);
    a = 2;  //去掉var,相當於改全局倉庫裏的值;
}
fn(); //1
alert(a); //2
var a = 1;
function fn(a){  //加參數
    alert(a); //往上找到參數a,到達不了 var a = 1; 所以預解析a = undefined
    a = 2;   //局域的a被改為a = 2,執行完後銷毀
}
fn(); //局部a = undefined
alert(a); //全局a = 1
var a = 1;
function fn(a){ 
    alert(a); 
    a = 2; 
}
fn(a);//執行時傳參進來 所以1
alert(a); //1
//獲取fn內的值方法一:

var str = ''         //1、定義
function fn(){
    var a = 'pig'
    str = a         //2、str 拿到
}
fn(); /////////////////////////////////////////     3、一定要執行;
alert(str)         //4、可找到pig
//获取fn内的值方法二:

function fn2(){
    var a = 'MM';
    fn3(a);
}
fn2()
function fn3(e){ //调用参数接收
    alert(e);  //e = a = 'MM'
}

写代码注意事项:
1、if条件判断非作用域;如下代码,但ff不能对下面的函数进行预解析;兼容性问题,所以若需定义全局变量或全局函数,不要在if或for循环里定义!

//不要這麼寫:
alert(a);  //undefined正常
alert(fn)  //if非作用域,理论上应该弹出整个fn内容chrome,但在ff上:fn is not defined
if(true){
  var a = 1
  function fn(){
    alert(123)
  }
}

//需這麼寫,變量與函數定義在if或for 外面
alert(a);  //undefined正常
alert(fn)  // function fn(){alert(123)}
  var a = 1
  function fn(){
    alert(123)
  }
if(true){
}
var btn = document.getElementsByTagName('input')
for (var i = 0; i < btn.length; i++) { //一個循環
  btn[i].onclick = function () {
    for (var i = 0; i < btn.length; i++) { //點擊每一個時,循環三次,正常
      btn[i].style.background = 'red'
    }
  }
}
for (var i = 0; i < btn.length; i++) { //一個循環3
  btn[i].onclick = function () {
    alert(i) //i = 3,執行完for後才點擊,i向上找,所以是3;
  }
}
for (var i = 0; i < btn.length; i++) { //一個循環3
  btn[i].onclick = function () { //這一塊是作用域,下面有var = 0,所以最開始 彈 i = undefined
    alert(i) // undefined
    for (var i = 0; i < btn.length; i++) { //如去掉var,則上面的i 必須往上找
      btn[i].style.background = 'red'
    }
  }
}

零JS筆記 | 數據類型

JS中的數據類型:number(NaN) string boolean function object(fn,[],{},null) undefined

var str = 'abc';
str.charAt(3) //下標

var obj = window; //object

var arr = [1] //
console.log(typeof arr); //object

function fn() {
  alert(this)
}
console.log(typeof fn); //function

obj.fn1 = function () {
  alert(1)
}
console.log(typeof obj.fn1); //object

var json = {
  name: 'elmok'
}
console.log(typeof json); //object

var u;
alert(u) //undefined 表示一種狀態
alert(typeof u) //undefined

顯式類型轉換:Number(),parseInt(),parseFloat()

//字符串轉數字 Number()
//可轉換的類型
var a = '100'
alert(a + 100) // '100100'

alert(Number(a) + 100) // 200

var b = '000100';
alert(Number(b)) //100

var c = '+100'
alert(Number(c)) //100

var d = ''; //d = '   '
alert(Number(d)); //0

var e = true
alert(Number(e)) //1

var arr = [] //['']-->0   [1,2,3]-->NaN  ['123']-->123
alert(Number(arr)) //0

var f = null
alert(Number(f)) // 0

//可轉換類型:parseInt(),parseFloat()
var i = '100px'
alert(parseInt(i)) //100,從左到右查看,若有非數字,則截斷;

var j = '+100'
alert(parseInt(j)) //從左到右,如遇到 + - 空格,則例外

var l = '100px'
alert(parseInt(l, 8)) // parseInt(l,進制)

var k = '10.1231231231元'
alert(parseFloat(k)) // 10.1231231231
//判斷是否有帶小數點  parseInt(n) == parseFloat(n)

無法轉換的數據類型:

1、NaN: not a number //不是數字 的 數字類型;
2、出現NaN表示進行了非法的操作;
3、NaN ==> false;
4、自已不等於自己;
5、isNaN 不是數字 返回true, 數字返回false
6、isNaN內部依靠Number()轉換

var fn = function () {
}
alert(Number(fn)) //NaN

var json = {
} //json無法轉

alert(Number(json)) //NaN

var g; //undefined
alert(Number(g)) //NaN

var h = '100px'
alert(Number(h)) //NaN

var o = Number('abc')
alert(o) //NaN

alert(typeof NaN) // number

//isNaN 不是數字 返回true,  是數字返回false ,即Number()能轉換的
alert(isNaN(123)) //false
alert(isNaN('abc')) //true
alert(isNaN(function () {
  alert(1)
})) //true
alert(isNaN('250')) //false ,使用Number('250')轉成250數字後返回false
alert(isNaN(true)) // false
alert(isNaN([])) //false
alert(isNaN(NaN)) //true

inp[1].onclick = function () {
  if (isNaN(inp[0].value)) { //有缺陷,如輸入 空格、true false
    alert('不是數字')
  } 
  else {
    alert('是數字')
  }
}

if (NaN) {
  alert('真')
} 
else {
  alert('假')
}

隱式類型轉換: - * / % 可讓字符串變成數字 + 可讓數字變成字符串 ++ -- 變成數字 > < 數字比較,字符串比較 !轉成布爾值 ==

alert(100 - '1') //99
alert('100' + 1) // 101
var n = '10'
alert(n++) //11
alert('10' > 5) // true '10'被轉成數字10
alert('10' < '5') // true 編碼位置比較
alert(!true) //false
alert(!'ok') //false
alert('2' == 2) //true

小技巧:

找字符:判斷typeof == 'string';
找數字:判斷typeof=='number' && 排除屬性NaN的數字類型:!isNaN(obj)
找可以轉成數字的:parseFloat(arr[i])==parseInt(arr[i])
找NaN:判斷typeof==='number' && 並且屬性不是數字:isNaN(obj)
var arr = [ '100px', 'abc'-6, [], -98765, 34, -2, 0, '300', , function(){alert(1);}, null, document, [], true, '200px'-30,'23.45元', 5, Number('abc'), function(){ alert(3); }, 'xyz'-90 ]

//找到數字,排除布爾值
for (var i = 0; i < arr.length; i++) { 
  if ((typeof arr[i]) == 'number' && !isNaN(arr[i])) {
    console.log(arr[i])
  }
}
//parseFloat会干掉0  所以要加上
var arrN = []
for (var i = 0; i < arr.length; i++) {
  if (parseFloat(arr[i]) == parseInt(arr[i])) {
    console.log(arr[i]);
    arrN.push(arr[i])
  }
}
console.log(Max(arrN));
function Max(arr) {
  var max = arr[0];
  for (var i = 0; i < arr.length; i++) {
    if (max < arr[i]) {
      max = arr[i]
    }
  }
  return max
}
//找字符串
for (var i = 0; i < arr.length; i++) {
  if (typeof arr[i] === 'string') {
    console.log(arr[i])
  }
}
//找到數字類型,並且是NaN
for (var i = 0; i < arr.length; i++) {
  if (typeof (arr[i]) == 'number' && isNaN(arr[i])) {
    console.log(i + ':' + arr[i]);
  }
}

零CSS3筆記 | 屬性操作

属性选择器[IE7+]
E[attr]
E[type="text"]
E[attr~="value"]以空格隔开,其中词列表中包含了一个value词
E[attr^="value"]以value开头
E[attr$="value"]以value结束的
E[attr*="value"]包含了value
E[attr|="value"]value或以“value-”开头的值(比如说zh-cn)



结构性伪类

of-type,关注以标签计算;

child,关注凡有子节点即计算,有&&的意思,缺一不成立;

E:nth-child(n) E的父元素中的第n个字节点,并且标签必须=E

p:nth-child(odd) 奇数

p:nth-child(even) 偶数

p:nth-child(2n)

E:nth-last-child(n) E的父元素中的第n个字节点,倒数计算



E:nth-of-type(n) E的父元素中的第n个字节点,只算类型E

E:nth-last-of-type(n) E父元素中的第n个字节点,只算类型E,倒数计算

E:empty E元素中没有子节点。注意:子节点包含文本节点

:first-child == :nth-child(1) IE9+
:last-child == :nth-last-child(1) IE9+
:first-of-type == :nth-of-type(1) IE9+
:last-of-type == :nth-last-of-type(1) IE9+

p:nth-of-type(2) 找到P标签父级下的第2个P标签 可能这种更靠谱
p:nth-last-of-type(2) 找到P标签父级下的倒数第2个P标签 可能这种更靠谱
p:empty 只要有东西即不成立,无论任何东西

p:only-child -->匹配那些是其父元素唯一孩子的 E 元素;IE9+
p:only-of-type -->根据 p 的类型,匹配那些在其兄弟里是唯一此类元素的 p 元素。IE9+

<div class='box1'>
<div>
<p>我是p,父级下只有我一个孩子,所以 only-child 及 only-of-type 都选中我</p>
</div>

<div>
<span>我是妹妹span</span>
<p>我是p,父级下只有妹妹span,没有别的哥哥弟弟p,但是也只有 only-of-type选中我;而only-child有妹妹span所以选不中</p>
</div>

<div>
<p>我是p,我有好多兄弟,所有我不能被选中</p>
<p>我是p,我有好多兄弟,所有我不能被选中</p>
</div>
</div>
.box1 p:only-child{background:green;color: #fff;}
.box1 p:only-of-type{background:peru;color: #fff;}

E:target 表示当前的URL片段的元素类型,这个元素必须是E
E:disabled 不可点击时的样式
E:enabled 可点击的样式
E:checked 已选中的checkbox或radio
E:first-line E元素中的第一行
E:first-letter E元素中的第一个字符
E::selection E元素在用户选中文字时
E::before 生成内容在E元素前
E:not(s) E元素不被匹配如 p:not(.tab) //不匹配带有class='tab'的元素
E~F表示E元素毗邻的F元素
Content 属性

<pre>#div1,#div2{width: 100px;height: 100px;background:red;display: none;}

div1:target,#div2:target{display: block;}

input:enabled{background:pink}
input:disabled{background:peru}
input:checked{width: 20px;height: 20px;}

label{ float: left; margin: 0 5px; overflow: hidden; position: relative;}
label input{ position: absolute; left: -50px; top: -50px;}
span{ float: left; width: 20px; height: 20px;border:1px solid #000;}
input:checked ~span{background:green}

p~h2{background:#f90}

.box p:first-line{background:#cdcd00}
.box p:first-letter{font-size: 30px;}

.box2 p::selection{background:darkmagenta; color:#fff;}

.box3:before{content:'before的内容';border:3px solid #000;padding-left: 10px;padding-right: 10px;}
.box3:after{content:'after的内容';border:3px solid #000;padding-left: 10px;padding-right: 10px;}

</pre>

See the Pen WQeqBP by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>



文本屬性

顏色模式:rgba(),应用:背景透明,颜色不透明,反向,边框透明,有bug;

文字陰影:text-shadow:x y blur color...

文字搭邊:-webkit-text-stroke:宽度 颜色 ,只支持webkit

Direction 定义文字排列方式(全兼容) 注意要配合unicode-bidi 一块使用

Text-overflow 定义省略文本的处理方式 clip 无省略号 Ellipsis 省略号 (注意配合overflow:hidden和white-space:nowrap一块使用)

p{
direction: rtl;        /*文字從右到左*/
unicode-bidi: bidi-override

/*文字超出點點省略*/
p{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis
}

自定義字體: @font-face
http://www.fontsquirrel.com/fontface/generator

    @font-face {
        font-family: 'chalk_marksregular';
        src: url('../font/chalkmars-webfont.eot');
        src: url('../font/chalkmars-webfont.eot?#iefix') format('embedded-opentype'),
        url('../font/chalkmars-webfont.woff2') format('woff2'),
        url('../font/chalkmars-webfont.woff') format('woff'),
        url('../font/chalkmars-webfont.ttf') format('truetype'),
        url('../font/chalkmars-webfont.svg#chalk_marksregular') format('svg');
        font-weight: normal;
        font-style: normal;
    }
    p{ font-family: 'chalk_marksregular'; font-size: 100px;transition: 1s}
    p:hover{ color: #f90;}


零JS筆記 | 最簡單的圖片切換 | index

最簡單的圖片切換一

window.onload = function () {
  var _prev = document.getElementById('prev'),
  _next = document.getElementById('next'),
  _txt = document.getElementById('txt'),
  _count = document.getElementById('count'),
  _img = document.getElementById('img'),
  num = 0,
  imgDate = {
    txt: ['校園美女一','校園美女二','校園美女三',
      '校園美女四','校園美女五','校園美女六'],
    img: ['../img/jc1.png','../img/jc2.png','../img/jc3.png',
        '../img/jc4.png','../img/jc5.png','../img/jc6.png']
  }
  //初始化

  tabImg()
  var len = imgDate.txt.length;
  _next.onclick = function () {
    num++;
    if (num == len) {
      num = 0;
    }
    tabImg()
  }
  _prev.onclick = function () {
    num--;
    if (num == - 1) {
      num = len - 1
    }
    tabImg()
  }
  function tabImg() {
    _txt.innerHTML = imgDate.txt[num];
    _count.innerHTML = (num + 1) + '/' + len;
    _img.src = imgDate.img[num];
  }
}

運行



最簡單的圖片切換二

注意:this指向;

步驟:初始化,寫循環每一個,合並函數[num = this.index;tab()],注意this指向;

on切換:1、全清空,當前添加;2、創建上一個狀態變量:prevLi = null; 清空上一個

for (var i = 0; i < lis.length; i++) {
  lis[i].className = '' //全清空
}
this.className = 'on'//當前添加

var prevLi = null; 
prevLi = li[num]; //先存上一個狀態;
prevLi.className = '' //點擊時把上一個狀態清除
prevLi = this; //再把當前付給上一個,形成循環
this.className = 'on' //當前添加

運行



菜單收縮

1、關鍵在於找元素;配合index,找到每一個h2,對應自已的ul;

2、每一個ul下,對應自己的li,即需要for套for;

3、for套for中,有fn的,不需要改i,無fn的,需要改變j;

4、判斷的方法,this.className = '';

5、找到li,因事件一致,可先存在數組裏,以數組來操作;

<ul id='list'>
    <li>
        <h2>aaaaaa</h2>
        <ul>
            <li> a-a-a-a-a-a</li>
            <li> a-a-a-a-a-a</li>
            <li> a-a-a-a-a-a</li>
        </ul>
    </li>
    .....
</ul>
var list = document.getElementById('list')
var h2 = document.getElementsByTagName('h2')
var _ul = list.getElementsByTagName('ul')
var _li = null;
var arrLi = [
];
var on = true;
for (var i = 0; i < h2.length; i++) {
  h2[i].index = i; //索引值對應 每個 h2 -> ul
  h2[i].onclick = function () {
    if (this.className == '') {
      //1、當前展開,其他收縮
      for (var i = 0; i < _ul.length; i++) {
        _ul[i].style.display = 'none'
        h2[i].className = ''
      }
      _ul[this.index].style.display = 'block'
      this.className = 'on'
    } 
    else {
      _ul[this.index].style.display = 'none'
      this.className = ''
    }
  }
}
for (var i = 0; i < _ul.length; i++) { //找到所有h2下 ul
  _li = _ul[i].getElementsByTagName('li') //找到所有li
  for (var j = 0; j < _li.length; j++) {
    arrLi.push(_li[j]); //所有li存放在arrLi裏
  }
}

//for 套for ,內部的fn,可不改i,無fn,必須改i
for (var i = 0; i < arrLi.length; i++) { //操作數組,即相當於操作li
  arrLi[i].onclick = function () {
    //2、當前點擊取消
    if (this.className == '') {
      for (var i = 0; i < arrLi.length; i++) {
        arrLi[i].className = ''
      }
      this.className = 'hover'
    } 
    else {
      this.className = ''
    }
  }
}

See the Pen doxZvW by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

簡單系統時間

var nowTime = new Date();//typeof object
下面出來的都數字類型:number
nowTime.getFullYear() //年
nowTime.getMonth() + 1 //月 從0開始算,所以需加1
nowTime.getDate() //日
nowTime.getDay() //星期
nowTime.getHours() //時
nowTime.getMinutes() //分
nowTime.getSeconds() //秒

Time()
setInterval(Time, 1000)
function Time() {
  var nowTime = new Date(); //typeof object
  var _year = nowTime.getFullYear();
  var _month = nowTime.getMonth() + 1;
  var _date = nowTime.getDate();
  var _week = nowTime.getDay();
  var _hours = nowTime.getHours()
  var _minutes = nowTime.getMinutes();
  var _seconds = nowTime.getSeconds();
    switch (_week){
        case 0:_week='星期日';break;
        case 1:_week='星期一';break;
        case 2:_week='星期二';break;
        case 3:_week='星期三';break;
        case 4:_week='星期四';break;
        case 5:_week='星期五';break;
        case 6:_week='星期六';
    }
  document.body.innerHTML = _year + '年' + _month + '月' + _date + '日  ' + _week + ' ' + toTwo(_hours) + ':' + toTwo(_minutes) + ':' + toTwo(_seconds);
}
function toTwo(n) {  //單數轉雙數
  return n = n < 10 ? '0' + n : '' + n;
}

圖片日期要點:日期共6位,使用str.charAt(i)獲取每一位數字,與圖片名字相對應

str = toTwo(_hours)+toTwo(_minutes)+toTwo(_seconds);
for(var i=0;i<str.length;i++){
    img[i].src = '../img/timePic/'+ str.charAt(i)+'.JPG'
}

運行

倒計時:
設置時間形式:
數字形式:new Date(2013,6,22,01,19,54)
字符串形式:new Date('June 10,2013 12:01:20')
思想:(未來時間 - 當前時間)/1000 = t //秒

套用

天:Math.floor(t/86400)
時:Math.floor(t%86400/3600)
分:Math.floor(t%86400%3600/60)
秒:t%60
Math.floor(t/86400)+'天'+ Math.floor(t%86400/3600)+'時'+ Math.floor(t%86400%3600/60)+'分'+t%60+'秒'

一月:January 简写Jan.
二月:February 简写Feb.
三月:March 简写Mar.
四月:April 简写Apr.
五月:May 简写May.
六月:June 简写Jun.
七月:July 简写Jul.
八月:August 简写Aug.
九月:September 简写Sep. / Sept.
十月:October 简写Oct.
十一月:November 简写Nov.
十二月:December 简写Dec.
開始時間:<input type="text" value="August 29,2015 1:39:59"/>
剩余時間:<input type="text"/>
<input type="button" value="Start"/>
var nowTime = new Date();
//var newTime = new Date(2013, 5, 22, 1, 39, 59);
var newTimeE = new Date('August 29,2014 1:39:59')
var t = Math.floor((newTimeE - nowTime) / 1000); //newTime - nowTime 毫秒單位 t為秒
var str = Math.floor(t / 86400) + '天' + Math.floor(t % 86400 / 3600) + '時' + Math.floor(t % 86400 % 3600 / 60) + '分' + t % 60 + '秒'
var inp = document.getElementsByTagName('input')
var inow = null;
var inew = null;
var timer = null;
inp[2].onclick = function () {
  clearInterval(timer)
  inew = new Date(inp[0].value)
  timer = setInterval(function () {
    inow = new Date();
    var tt = Math.floor((inew - inow) / 1000);
    if (tt >= 0) {
      var str = Math.floor(tt / 86400) + '天' + Math.floor(tt % 86400 / 3600) + '時' + Math.floor(tt % 86400 % 3600 / 60) + '分' + tt % 60 + '秒'
      inp[1].value = str;
    } 
    else { //倒計時完成後動作
      clearInterval(timer)
    }
  }, 1000)
}

new Date().getTime() //時間戳:1970年1月1日0點0分0秒0毫秒 距離現在多長時間,毫秒為單位