Javascript笔记

基础

基本类型

//严格区分大小写
Number.MAX_VALUE
Number.MIN_VALUE
Infinity正无穷
-Infinity负无穷
NaN:Not A Number也是数字

null的值是null,存放空对象,typeof为object
undefined的类型值就是undefined,变量未赋值就是undefined,统一配发为undefined

类型转换

  • String
//方法一
//Number Boolean 可以
//null undefined不行
xxx.toString;
//方法二
//都可以
String(a);
  • Number
//方法一
//"abc"结果为NaN
//""为0
//null为0
//true为1
//false为0
//undefined为NaN
Number();
//方法二
//可以取出"123px"中的123,Number()方式不行
parseInt(a);
//指定进制
parseInt(b,10);
parseFloat(a);

//Boolean

//a!=0 true
//0  NaN false
//String true
// ""  false
//null false
//undefined false
//Object true
Boolean(a);

运算符

typeof 返回 String
//字符串加法会拼串
//NaN+任何数为NaN
//任何值做* /都会转换成Number

立即执行函数

//(函数对象)();
 (function () {
alert("立即执行函数")
        })();
 (function (a,b) {
     alert(a+b)
 })(123,456);

枚举对象

 var  obj={
     name:123,
     age:321
 }
 for(var n in obj ){
     //输出属性
     console.log(n);
     //输出值
     console.log(obj[n]);
 }

this

  • 以函数形式调用,this指向window
  fun();
//即window.fun();
//this是window
  • 以方法形式调用,this就是调用方法的对象
  obj.name
//this为obj
  • 以构造函数的形式调用时,this就是新创建的那个对象
    function Person(name, age, gender) {
                this.name = name;
                this.age = age;
                this.gender = gender;
        }

原型对象

 function MyClass() {

        }

        let myClass = new MyClass();
        //true
        console.log(myClass.__proto__ == MyClass.prototype);
    function MyClass() {

        }

         MyClass.prototype.name = "我是原型中的名字"
        let myClass = new MyClass();
        
        console.log(myClass.name);
        //true
        console.log(MyClass.hasOwnProperty("name")
        );
        //false
        console.log(MyClass.hasOwnProperty("hasOwnProperty")
        );
        //false
        console.log(MyClass.__proto__.hasOwnProperty("hasOwnProperty")
        );
        //false
        console.log(myClass.__proto__.hasOwnProperty("hasOwnProperty")
        );
        //true
        console.log(myClass.__proto__.__proto__.hasOwnProperty("hasOwnProperty")
        );
//Object
console.log(myClass.__proto__);
//Object
console.log(myClass.__proto__.__proto__);
//null
console.log(myClass.__proto__.__proto__.__proto__);

重写toString方法

Person.prototype.toString=function () {
    return "Person[name="+this.name+",age="+this.age+"]";
}

数组

方法

array.push();
array.pop();
array.shift();
array.unshift();

forEach遍历

array.forEach(function (value,index,obj) {
console.log(value);
console.log(index);
//true
console.log(obj==array);
});

sort排序

   let array = new Array(1,6,3,7,4);
        let numbers = array.sort(function (a, b) {
        //a-b>1,交换位置,升序排列
        //a-b<=0,不交换位置,降序排列
            return a - b;
        });
        console.log(numbers);

随机数

//生成1-10
      for(var i=0;i<100;i++){
            console.log(Math.round(Math.random()*10));
        }
 //生成2-10
      for(var i=0;i<100;i++){
            console.log(Math.round(Math.random()*8+2));
        }

filter()

  • 语法
Array.filter(function(currentValue, indedx, arr), thisValue)
  • 其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
      函数的第一个参数 currentValue 也为必须,代表当前元素的值。
  • 实例
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
  return num > 5;
});
console.log(res);  // [6, 7, 8, 9, 10]

DOM对象

绑定事件

<body>
<button id="btn">
    按钮
</button>
<script type="text/javascript">
    let btn = document.getElementById("btn");
    btn.ondblclick=function(){
        alert("告警");
    }
</body>

后置加载js

<head>
    <meta charset="UTF-8">
    <title>dom</title>
    <script type="text/javascript">
      window.onload=function () {
          let btn = document.getElementById("btn");
          btn.ondblclick=function(){
              alert("告警");
          }
      }
    </script>
</head>
<body>
<button id="btn">
    按钮
</button>

获取对象

 <script type="text/javascript">
      window.onload=function () {
          let btn = document.getElementById("btn");
          let tagName = document.getElementsByTagName("div");
          let gender = document.getElementsByName("gender");
          }
      }
    </script>
var body=document.body;
var html=document.documentelement;
var all=document.all;
var className=document.getElementsByClassName();
//class
var div=document.querySelector(".box");
//id
var div=document.querySelector("#box");
//返回数组
var divs=document.querySelectorAll(".box");

增删改

 var div = document.createElement("div");
    //增
    var li =document.createElement("li");
    li.innerHTML="广州";
    div.appendChild(li);
    //删
    div.removeChild(li);
    //改
    div.replaceChild(new,old);
    //插入
    div.insertBefore(new,old);

获取样式

    //不能读取头文件中的样式设置,只能读取内联样式
    id.style.width
    //IE8
    id.currrentStyle.width
    //null为伪元素,较通用
    getComputedStyle((id,null).width);

返回样式属性(只读)

id.clientWidth;
id.clientHeight;
//内容区+padding
id.offsetWidth;
id.offsetHeight;
//定位开启了position:absolute/relative定位功能祖先元素
id.offsetParent;
//滚动区长宽,此时的id.clientWidth减去滚动条的宽度
id.scrollWidth;
id.scrollHeight;
//滚动条滚动距离
id.scrollTop;
id.scrollLeft;

获取当前样式函数(只读)

     function getStyle(obj, name) {
                if (window.getComputedStyle) {
                    return getComputedStyle(obj, null)[name];
                } else {
                    return obj.currentStyle[name];
                }
            }

事件

Confirm

//返回值为布尔类型
var flag=confirm("确认删除吗?");

onscroll

//滚动条是否到底
id.onscroll=function () {
    id.scrollHeight-id.scrollTop==id.clientHeight;
}

偏移量

    <script type="text/javascript">
        window.onload = function () {
            let area = document.getElementById("area");
            let msg = document.getElementById("msg");
            area.onmousemove = function (event) {
                // if(!event){
                //     event=window.event;
                // }
                event = event || window.event;
                //event.pageX表示视图偏移量
                //event.clientX表示页面偏移量
                let x = event.clientX;
                let y = event.clientY;
                msg.innerHTML = ("x=" + x + ",y=" + y);
            };
        };
    </script>
</head>
<body>
<div id="area" style="width:500px;height: 200px;"></div>
<div id="msg" style="width:500px;height: 100px"></div>
</body>

冒泡

//取消冒泡
event.cancelBubble=true;

委派

  • 将事件统一绑定给元素的共同祖先元素,后代元素上的事件触发,会冒泡到祖先元素的响应函数

事件绑定

  • event.target
//指定响应事件对象的属性
event.target.className=="link";
  • addEventListener
  • 为一个事件绑定多个函数
     let btn01 = document.getElementById("btn01");
         btn01.addEventListener("click", function () {
                alert("btn01");
            },false);

拖拽

        window.onload = function () {
            let box1 = document.getElementById("box1");
            box1.onmousedown = function (event) {
                let oX = event.pageX - box1.offsetLeft;
                let oY = event.pageY - box1.offsetTop;
                document.onmousemove = function (event) {
                    let pageX = event.pageX;
                    let pageY = event.pageY;
                    box1.style.left = pageX - oX + "px";
                    box1.style.top = pageY - oY + "px";
                }
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }
        }

滚轮事件(注意火狐)

 <style type="text/css">
        #box1 {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            let box1 = document.getElementById("box1");
            box1.onwheel = function (event) {
                let wheelDelta = event.wheelDelta;
                if (wheelDelta > 0) {
                    box1.style.height = box1.clientHeight + 10 + "px";
                } else {
                    box1.style.height = box1.clientHeight - 10 + "px";
                }
            }
        }
    </script>
</head>
<body>
<div id="box1"></div>
</body>

键盘事件

let input = document.getElementsByTagName("input")[0];
input.onkeydown = function (event) {
     if (event.ctrlKey == 1) {
         alert(1)
         }
     }

BOM对象

navigator.userAgent;
history.back();
history.forward();
history.go(number);
//修改location为完整路径,页面会跳转,并生成历史记录
location="https://www.bing.com/";
//功能同上
location.assign("https://www.bing.com/");
//刷新,true可以强制清楚缓存
location.reload(true);
//不会生成历史记录,不能回退 
location.replace("https://www.bing.com/");

定时器

  • 定时器的启动与停止
   <script type="text/javascript">
        window.onload = function () {
            let count = document.getElementById("count");
            let num = "0";
            let timer = setInterval(function () {
                count.innerHTML = num;
                num++;
                if (num > 10) {
                    clearInterval(timer)
                }
            }, 500);
        }
    </script>
  • 自动播放
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/css">
        #pic #pre #next {
            width: 300px;
            height: 400px;
            margin: 0 auto;
            text-align: center;
        }
    </script>
    <script type="text/javascript">
        window.onload = function () {
            let info = document.getElementById("info");
            let img = document.getElementById("img");
            var array = new Array("img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg");
            var index = 0;
            info.innerText = "总共有" + array.length + "张图片,现在是第" + (array[index] + 1) + "张图片";
            let pre = document.getElementById("pre");
            pre.onclick = function () {
                index--;
                img.src = array[index];
                if (index < 0) {
                    index = array.length;
                }
                info.innerText = "总共有" + array.length + "张图片,现在是第" + (array[index] + 1) + "张图片";
            }
            let next = document.getElementById("next");
            next.onclick = function () {
                index++;
                if (index >= array.length) {
                    index = 0;
                }
                img.src = array[index];
                info.innerText = "总共有" + array.length + "张图片,现在是第" + (array[index] + 1) + "张图片";
            }
            let auto = document.getElementById("auto");
            let stop = document.getElementById("stop");
            let timer;
            auto.onclick = function () {
                clearInterval(timer)
                timer = setInterval(function () {
                    img.src = array[index];
                    index++;
                    index = index % array.length;
                }, 1000);
            }
            stop.onclick = function () {
                //可以接收任何参数,不会报错
                clearInterval(timer);
            }
        }
    </script>
</head>
<body>
<div id="info"></div>
<div id="pic">
    <img id="img" src="img/1.jpg"/>
</div>
<button id="pre">上一张</button>
<button id="next">下一张</button>
<button id="auto">自动播放</button>
<button id="stop">停止播放</button>
</body>
</html>
  • 无卡顿移动
    <script type="text/javascript">
        window.onload = function () {

            let box1 = document.getElementById("box1");
            var speed = 10;
            var dir = 0;
            setInterval(function () {
                switch (dir) {
                    case  37:
                        box1.style.left = box1.offsetLeft - speed + "px";
                        break;
                    case  39:
                        box1.style.left = box1.offsetLeft + speed + "px";
                        break;

                    case  38:
                        box1.style.top = box1.offsetTop - speed + "px";
                        break;

                    case  40:
                        box1.style.top = box1.offsetTop + speed + "px";
                        break;

                }
            }, 100);
            document.onkeydown = function (event) {
                if (event.altKey) {
                    speed = 50;
                } else {
                    speed = 10;
                }
                dir = event.keyCode;
            }

            document.onkeyup = function () {
                dir = 0;
            }
        }
    </script>

延时调用

        //定时器的启动与停止
        let timeout = setTimeout(function () {
            console.log("延时调用")
        }, 3000);
        // clearTimeout(timeout);

工具类

function getStyle(obj, name) {
    if (window.getComputedStyle) {
        return getComputedStyle(obj, null)[name];
    } else {
        return obj.currentStyle[name];
    }
}

function getMove(obj,speed,target,attribute,callback){
    let current =parseInt(getStyle(obj,attribute)) ;
    if (current>=target){
        speed=-speed;
    }
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        let value = parseInt(getStyle(obj, attribute));
        valueNew=value+speed;
        if (speed>0&&valueNew>=target){
            valueNew=target;
            obj.style[attribute] = valueNew + "px";
            clearInterval(obj.timer);
            //放在 clearInterval(obj.timer);后面
            callback&&callback();
        }
        else if (speed<0&&valueNew<target){
            valueNew=target;
            obj.style[attribute] = valueNew + "px";
            clearInterval(obj.timer);
            callback&&callback();
        }
        else {
            obj.style[attribute] = valueNew + "px";
        }
    }, 50);
}

轮播图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="methods.js"></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        #outer {
            width: 240px;
            height: 310px;
            margin: 50px auto;
            background-color: yellowgreen;
            padding: 0px;
            position: relative;
            overflow: hidden;
        }

        ul {
            position: absolute;
        }

        li {
            list-style: none;
            float: left;
            margin: 10px;

        }

        #navDiv {
            position: absolute;
            bottom: 3%;

        }

        #navDiv a {
            float: left;
            width: 10px;
            height: 10px;
            background-color: palevioletred;
            margin: 0 5px;
            opacity: 0.8;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            var imgArray = document.getElementsByTagName("img");
            let ul = document.getElementsByTagName("ul")[0];
            ul.style.width = 240 * imgArray.length + "px";
            let navDiv = document.getElementById("navDiv");

            let outer = document.getElementById("outer");
            navDiv.style.left = (outer.offsetWidth - navDiv.offsetWidth) / 2 + "px";
            let allA = document.getElementsByTagName("a");
            var index = 0;
            allA[index].style.backgroundColor = "black";
            let timer;

            function setA() {
                if (index >= imgArray.length - 1) {
                    index = 0;
                    ul.style.left = 0 + "px";
                }
                for (var i = 0; i < allA.length; i++) {
                    allA[i].style.backgroundColor = "";
                }
                allA[index].style.backgroundColor = "black";
            }

            for (var i = 0; i < allA.length; i++) {
                allA[i].num = i;
                allA[i].onclick = function () {
                    clearInterval(timer);
                    index = this.num;
                    // ul.style.left = -240 * index + "px";
                    setA();
                    getMove(ul, 240, -240 * index, "left", function () {
                        autoChange();
                    })
                }
            }
            autoChange();
            function autoChange() {
                timer = setInterval(function () {
                    index++;
                    index %= imgArray.length;
                    getMove(ul, 40, -240 * index, "left", function () {
                        setA();
                    });
                }, 2000);
            }
        }
    </script>
</head>
<body>
<div id="outer">
    <ul>
        <li>
            <img src="img/1.jpg">
        </li>
        <li>
            <img src="img/2.jpg">
        </li>
        <li>
            <img src="img/4.jpg">
        </li>
        <!--        最后一张和第一张图片相同-->
        <li>
            <img src="img/1.jpg">
        </li>

    </ul>
    <div id="navDiv">
        <a href="javascript:;">
        </a>
        <a href="javascript:;">
        </a>
        <a href="javascript:;">
        </a>
    </div>
</div>
</body>
</html>

Json

//JSON字符串转对象
JSON.parse(obj);
//对象转JSON字符串
JSON.stringify(obj);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值