js,jquery

一.Javascript

js发展历史简述:https://www.cnblogs.com/clschao/articles/10092896.html

js介绍:https://www.cnblogs.com/Eva-J/articles/11261881.html

ECMAScript:JavaScript的语法标准。包括变量、表达式、运算符、函数、if语句、for语句等。

DOM:文档对象模型,操作网页上的元素的API。比如让盒子移动、变色、轮播图等。

BOM:浏览器对象模型,操作浏览器部分功能的API。比如让浏览器自动滚动。
JavaScript基础分为三部分

1.ECMAScript(现在主学es5)

1.1 js引入和script

<script>
    alert("hello")
<script>
方式一:js代码写在script标签里面(耦合性大,不好..)
<script src="xx.js">
    js代码
<script>
方式二:引入外部js,好啊

1.2 输入输出(alert,console,prompt)

console.log("xx")  #在控制台打印
prompt(">>")      #在浏览器上端输出 相当于input()
alert("sss")          #弹出框
输入输出

1.3 js匿名函数

在js中,所有的函数都可以看作是Function对象。

简单来说,匿名函数就是没有名字的函数,在js中,要定义函数必须要有声明函数function。

<script>
    function 函数名(){
        //代码
    };
</script>
一般函数格式
<script>
    function (){
        //代码
    }
</script>
匿名函数格式

在匿名函数中,只有函数声明,没有函数名字,因此在调用时要给匿名函数赋一个变量来接受。

<script>
    f=function (){
        //代码
    }
    f();          //调用函数
</script>
匿名函数执行

匿名函数自执行(将整个函数用括号括起来,最后在用小括号调用):

<script>
    (function (a,b){
        alert(a);
    })(1,2);
</script>
匿名函数自执行

1.4 js正则\Math方法

1.4.1 js简单正则

var reg = RegExp("正则表达式")  #创建一个正则
var reg2 = /正则表达式/      #js中的正则表达式两边加上//,表达式中的特殊字符不会被转义

var s = "Aalex1234"
s.match(/\d/g)   #g加在正则外面,返回['1','2','3','4'] 列表
s.match(/a/i)      #i加在正则外面,不区分大小写
s.match(/a/gi)     #返回列表
js正则

1.4.2 Math方法

Math.abs(x)      返回数的绝对值。
pow(x,y)    返回 x 的 y 次幂。
round(x)    把数四舍五入为最接近的整数。
sqrt(x)     返回数的平方根。
exp(x)      返回 e 的指数。
log(x)      返回数的自然对数(底为e)。
sin(x)      返回数的正弦。
tan(x)      返回角的正切。
其他方法
var x = 1.234;
//天花板函数  表示大于等于 x,并且与它最接近的整数是2
var a = Math.ceil(x);
console.log(a);//2
Math.floor 向下取整,'地板函数'
console.log(Math.max(2,5));//5
console.log(Math.min(2,5));//2
max/min 求两个数的最大值和最小值
var ran = Math.random();
console.log(ran);[0,1)

如果让你取100-200之间的随机数,怎么做?
公式:min - max之间的随机数: min+Math.random()*(max-min)
随机数 Math.random() 区间[0,1)

1.5 JSON对象\数据类型之间的转换

1.5.1 JSON对象

var str1 = '{"name": "chao", "age": 18}';
var obj1 = {"name": "chao", "age": 18};
// JSON字符串转换成对象
var obj = JSON.parse(str1); 
// 对象转换成JSON字符串
var str = JSON.stringify(obj1);
js中JSON对象转换

1.5.2 数据类型之间的转换

parseInt() :字符串转数字
parseFloat() : 字符串转小数 
String()和.toString:转字符串
Boolean():任何数据类型都可以转成布尔值
数据类型之间的转换

1.6 Date

1.6.1.简单方法

1.6.2 创建Date对象

//创建日期对象
var myDate=new Date();
        
//获取一个月中的某一天
console.log(myDate.getDate());

//返回本地时间
console.log(myDate().toLocalString());//2018/5/27 下午10:36:23
简单使用(创建、获取某天、返回本地时间)

 

2.DOM操作

DOM树介绍

 

 

上图可知:在HTML中,一切都是节点

元素节点:HTML标签。
文本节点:标签中的文字(比如标签之间的空格、换行)
属性节点::标签的属性。
html中,一切都是节点

在DOM中,document就是整个文档树。3个重要东西:节点获取、节点操作、事件绑定。

2.1 节点获取

1.直接查找(三种方式找到DOM节点)

var div1 = document.getElementById("box1");      //方式一:通过id获取单个标签
var arr1 = document.getElementsByClassName("hehe");  //方式二:通过 类名 获得 标签数组,所以有s
var arr2 = document.getElementsByTagName("div1");     //方式三(几乎不用):通过 标签名 获得 标签数组,所以有s
//其中方式二、方式三获取的是标签数组,那么习惯性是先遍历之后再使用。

2.间接查找

父节点:
parentNode:指的是元素节点(标签)

兄弟节点:
nextSibling:指的是下一个节点(包括标签、空文档和换行节点)
nextElementSibling:指的是下一个元素节点(标签)
previousSibling:指的是上一个节点(包括标签、空文档和换行节点)
previousElementSibling:指的是下一个元素节点(标签)

子节点:
firstChild:指的是第一个子节点(包括标签、空文档和换行节点)
firstElementChild:指的是第一个元素节点(标签)
lastChild:指的是最后一个子节点(包括标签、空文档和换行节点)
lastElementChild:指的是最后一个元素节点(标签)

所有子节点:
childNodes: childNodes[0]第一个子节点(包括标签、空文档和换行节点)
children:children[0]第一个子节点(标签)
说明

2.2 节点操作

节点本身操作

//创建节点
新的标签(元素节点) = document.createElement("标签名");

//插入节点
父节点.appendChild(新的子节点);//方式1:父节点的最后插入一个新的子节点。 
父节点.insertBefore(新的子节点,作为参考的子节点);//方式2:在参考节点前插入一个新的节点。如果参考节点为null,那么他将在父节点最后插入一个子节点。

//删除节点
父节点.removeChild(子节点);//用父节点删除子节点。必须要指定是删除哪个子节点。
node1.parentNode.removeChild(node1);//删除自己这个节点

//复制节点
要复制的节点.cloneNode();       //括号里不带参数和带参数false,效果是一样的。不带参数/带参数false:只复制节点本身,不复制子节点。
要复制的节点.cloneNode(true);   //带参数true:既复制节点本身,也复制其所有的子节点。

//替换节点
父节点.replaceChild(newnode, 某个节点);   //找到这个父标签里面的要被替换的子标签,然后用新的标签将该子标签替换掉
createElement、appendChild、removeChild、cloneNode...

节点属性操作

//获取节点属性值
元素节点.getAttribute("属性名称");

//设置节点属性值
元素节点.setAttribute(属性名, 新的属性值);

//删除节点属性
元素节点.removeAttribute(属性名);
getAttribute、setAttribute、removeAttribute

节点文本操作

var divEle = document.getElementById("d1")
divEle.innerText  #输入这个指令,一执行就能获取该标签和内部所有标签的文本内容
divEle.innerHTML  #获取的是该标签内的所有内容,包括文本和标签
innerText、innerHTML

class操作

className  获取所有样式类名(字符串)
首先获取标签对象
标签对象.classList.remove(cls)  删除指定类
classList.add(cls)  添加类
classList.contains(cls)  存在返回true,否则返回false
classList.toggle(cls)  存在就删除,否则添加,toggle的意思是切换,有了就给你删除,如果没有就给你加一个
classList.remove()、add()、contains()、toggle()

指定css操作

obj.style.backgroundColor="red"

1.对于没有中横线的CSS属性一般直接使用style.属性名即可
obj.style.margin
obj.style.width
obj.style.left
obj.style.position

2.对含有中横线的CSS属性,将中横线后面的第一个字母换成大写即可
obj.style.marginTop
obj.style.borderLeftWidth
obj.style.zIndex
obj.style.fontFamily
obj.style.width...

2.3 事件

1.事件三要素:事件源、事件、事件驱动程序

<body>
<div id="box1"></div>

<script type="text/javascript">
    // 1、获取事件源
    var div = document.getElementById("box1");
    // 2、绑定事件
    div.onclick = function () {
        // 3、书写事件驱动程序
        alert("我是弹出的内容");
    }
</script>
</body>
事件三要素代码举例

2.事件绑定

 

<input type="button" value="+" onclick="fun1()">
<script>
    function fun1(){
        alert(123);
    }
</script>


//带this
<div class="div1" onclick="fun1(this)">div1</div>
<script>
    function fun1(e){
        alert(e.innerHTML);
    }
</script>
事件绑定方式一:属性中绑定
<div class="div1">div1</div>
<script>
    var tmp=document.getElementsByClassName("div1")[0];
    tmp.onclick=function(){                 //onclick后不跟括号
        alert(123);
    }
</script>


//带this
<div class="div1">div1</div>
<script>
    var tmp=document.getElementsByClassName("div1")[0];
    tmp.onclick=function(){
        alert(this.innerHTML);              //this也是指代标签
    }
</script>
事件绑定方式二:script中绑定

onscroll事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            height: 2000px;
            background-color: #8c222c;
        }
    </style>
</head>
<body>
<div></div>
<script>
    div1 = document.getElementsByTagName("div")[0];
    window.onscroll = function () {
        if(document.documentElement.scrollTop>500){
            console.log(">500")
        }else {
            console.log("sss")
        }
    }
</script>
</body>
</html>
onscroll事件(浏览器滚动条滚动)

onchange事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <select name="s1" id="s1">
            <option value="nnnn">11</option>
            <option value="2">22</option>
            <option value="3">33</option>
            <option value="4">44</option>
            <option value="5">55</option>
        </select>
    </div>
</body>
<script>
    s1 = document.getElementById("s1");
    s1.onchange = function () {
        //alert(s1.options[s1.options.selectedIndex].value);
        console.log(s1.value)  //得到选择的value值
    }
</script>
</html>
select的onchange事件 

 

3.BOM操作

window.open(url,target)

//url:要打开的地址。
//target:新窗口的位置。可以是:_blank 、_self、 _parent 父框架。

window.close() - 关闭当前窗口 (只能关闭用js的window.open()打开的页面,了解一下就行了)
打开窗口(window.open)、关闭窗口(window.close)
window.innerHeight - 浏览器窗口的内部高度
window.innerWidth - 浏览器窗口的内部宽度 
获取窗口宽高(window.innerWidth窗口左右移动会随着变大变小)

3.1 定时器

在js中的定时器分两种:1、setTimeout() 2、setInterval()

/定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器
setTimeOut(fun,1000)
/实时刷新  时间单位为毫秒  
var t = setInterval('refreshQuery()',8000);   
/* 刷新查询 */  
function refreshQuery(){  
  console.log('每8秒调一次') 
}
window.clearInterval(t)
setInterval(fun,1000)

3.2 Location对象

window.location可以简写成location。location相当于浏览器地址栏,可以将url解析成独立的片段。

<script>

    setTimeout(function () {
        location.href = "http://www.baidu.com";
    }, 5000);
</script>
5秒跳转到百度 location.href="http://www.baidu.com"
setTimeout(function(){
         //3秒之后让网页整个刷新
    window.location.reload();
            
            
},3000)
页面刷新 location.reload()

3.3 history对象

history.back()
history.go(-1):0是刷新
后退(history.back())
history.forward()
history.go(1)
前进(histtory.forward())

3.4 onload

在html+js中,经常出现js加载完而html没有加载完,解决方法如下
方法一:将script语句放在</body>前面,等待所有标签执行完再执行script语句

方法二:在body标签中添加:onload=“fun()”,然后将script语句封装在fun()函数中

<body onload='fun1()'>
    <script>
        function fun1(){
            alert("2134");
        }
    </script>
</body>
方法二

方法三:在head标签中添加window.onload=function(){}

<head>
    <script>
        window.onload=function(){}
    </script>
</head> 
方法三

 

二.jquery

1.jquery简介

1.1 什么是jquery

jQuery 是 js 的一个库,封装了我们开发过程中常用的一些功能,方便我们调用,提高开发效率。
js库是把我们常用的复杂功能封装到简单的方法中,我们用的时候,将库直接引入然后调用方法即可。

1.2 jquery两大特点

隐式迭代:隐式 对应的是 显式。隐式迭代的意思是:在方法的内部进行循环遍历,而不用我们自己再进行循环,简化我们的操作,方便我们调用。
链式操作:比如.show()和.html()可以连写成.show().html()。

1.3 jquery下载

下载 :jQuery有两个文件,一个是jquery-3.4.1.js(未压缩版),一个是jquery-3.4.1.min.js(压缩版,推荐项目上线时使用)

1.4 创建jquery对象

$("选择器")
$(dom对象)

dom对象:
    1.a=document.getElementById("xx");
    2."<a href='http://www.baidu.com'>百度一下</a>"
jquery对象的2种创建方式

1.5 dom对象和jquery对象的相互转换

dom对象->jq对象:$(dom对象)
jq对象->dom对象:jq对象[index]
dom对象->jq对象、jq对象->dom对象

2.jquery查找标签

2.1 通过选择器

基本选择器、层级选择器、属性选择器

$("#id")         //id选择器
$("tagName")     //标签选择器
$(".className")  //class选择器
$("*")           //通用选择器

$("div.c1")      // 交集选择器 找到有含有c1类的div标签
$("#id, .className, tagName") //并集选择器,逗号相隔
基本选择器
$("x y");// x的所有后代y(子子孙孙)
$("x > y");// x的所有儿子y(儿子)
$("x + y")// 找到所有紧挨在x后面的y
$("x ~ y")// x之后所有的兄弟y
层级选择器
$('[href]')       //找所有含href属性的标签
$('a[href]')      //找所有含href属性的a标签
$('a[title="luffy"]') //找所有title属性是luffy的a标签
$('a[title="baidu"]') //找所有title属性不是百度的a标签
$('a[href^="https"]') //找所有href属性以https开头的a标签
$('a[href$="html"]')  //找所有href属性以html结尾的a标签
$('a[href*="i"]')  //找所有href属性中含有i的a标签
$('a[href][title="luffy"]') //找所有含有href属性且title属性=luffy的a标签 
属性选择器

2.2 通过筛选器

:first // 第一个
:last // 最后一个
:eq(index)// 索引等于index的那个元素
:even // 匹配所有索引值为偶数的元素,从 0 开始计数
:odd // 匹配所有索引值为奇数的元素,从 0 开始计数
:gt(index)// 匹配所有大于给定索引值的元素
:lt(index)// 匹配所有小于给定索引值的元素
:not(元素选择器)// 移除所有满足not条件的标签
:has(元素选择器)// 根据含有某个后代筛选
基本筛选器
type属性筛选器:
:text
:password
:file
:radio
:checkbox
:submit
:reset
:button

其他属性筛选器
:enabled
:disabled
:checked
:selected
表单筛选器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../练习/jquery-3.4.1.min.js"></script>

</head>
<body>
<div></div>
<div id="app">
    apppppppppppppppppp
    <p>11</p>
    <p>32</p>
    <p>4</p>
</div>
<div class="box bb"><span>spane</span></div>
<div class="box"></div>
<div></div>

<script>
    console.log($("p:first")[0]);
    console.log($("p:eq(1)"));
    $("p:even").css("background-color","red");
    $("div:gt(1)").css("color","yellow");
    $(".box:not(.bb)").css("background-color","pink");
    console.log($(".box:has(span)"));  //找到有子元素span标签的以box为类名的标签
</script>
</body>
</html>
示例代码

2.3 通过筛选器方法

//找兄弟
$("#id").siblings();// 兄弟们,不包含自己,.siblings('#id'),可以在添加选择器进行进一步筛选

//找弟弟
$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2") #直到找到id为i2的标签就结束查找,不包含它

//找哥哥
$("#id").prev()
$("#id").prevAll()
$("#id").prevUntil("#i2")
找兄弟、弟弟、哥哥
//找祖辈
$("#id").parent()
$("#id").parents()  // 查找当前元素的所有的父辈元素(爷爷辈、祖先辈都找到)
$("#id").parentsUntil('body') // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止,这里直到body标签,不包含body标签,基本选择器都可以放到这里面使用。
找祖辈
$("#id").children();// 儿子们
找儿子
//过滤
$("div").first() // 获取匹配的第一个元素
$("div").last() // 获取匹配的最后一个元素
$("div").eq(n) // 索引值等于指定值的元素,n是索引
$("div").not() // 从匹配元素的集合中删除与指定表达式匹配的元素
$("div").find("p") //后代选择器,在所有div标签中找后代的p标签
$("div").filter(".c1")  // 交集选择器,从结果集中过滤出有c1样式类的
$("div").has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
过滤

3.jquery操作标签

3.1 标签内文本操作

//获取标签中的所有内容
$("#box").html()

//设置标签中所有内容
$("#box").html("<a href='http://www.baidu.com'>百度一下</a>");
html 标签中所有的内容
//获取所有标签的文本内容
$("#box").text();

//设置当前标签的内容
$('#box').text('<a href="https://www.baidu.com">百度一下</a>');
text 所有标签的文本内容

3.2 标签操作

1.标签增加(如果被添加的标签原本就在文档树中,相当于移动)

//追加:
父jq对象.append(子jq对象)
子jq对象.appendTo(父jq对象)

//头部添加:
父jq对象.append(子jq对象)
子jq对象.appendTo(父jq对象)
追加儿子:append appendTo prepend prependTo
//添加哥哥
参考点.before(要插入的)     
要插入的.insertbefore(参考点)

//添加弟弟 
参考点.after(要插入的)      
要插入的.insertAfter(参考点)
兄弟关系:before insertbefore after insertAfter

2.标签删除、修改、克隆

remove : 删除标签和事件
detach : 删除标签,保留事件
empty : 清空内容标签,自己被保留
删除:remove detach empty
replaceWith : a.replaceWith(b)  用b替换a
replaceAll : a.replaceAll(b)    用a替换b
修改:replaceWith replaceAll
var btn = $(this).clone()      //克隆标签但不能克隆事件
var btn = $(this).clone(true)  //克隆标签和事件
复制:clone

3.3 标签属性操作

//获取属性的值
$('a').attr('href')
//设置/修改属性的值
$('a').attr('href','http://www.baidu.com')
//设置多个属性值
$('a').attr({'href':'http://www.baidu.com','title':'baidu'})

removeAttr
$('a').removeAttr('title') //删除title属性


//如果一个标签只有true和false两种情况,适合用prop处理
$(':checkbox:checked').prop('checked') //获取值
$(':checkbox:checked').prop('checked',false) //表示取消选中
如果设置/获取的结果是true表示选中,false表示取消选中
attr() prop()

3.4 class类操作

添加类   addClass
$('div').addClass('red')        //添加一个类
$('div').addClass('red bigger') //添加多个类

删除类   removeClass
$('div').removeClass('bigger')  //删除一个类
$('div').removeClass('red bigger')

转换类   toggleClass             //有即删 无即加
$('div').toggleClass('red')      
$('div').toggleClass('red bigger')
addClass removeClass toggleClass
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red{
            color: red;
        }
    </style>
    <script src="../练习2/jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="divs">
    <div id="div1">
        <p>1111</p>
        <p>2222</p>
        <p>3333</p>
    </div>
    <button onclick="fun()"></button>
</div>
<script>
    function fun(){
        $("#div1").toggleClass("red");
    }

</script>
</body>
</html>
toggleClass示例

3.5 value值操作

$(input).val()
$(':text').val('值')
$(':password').val('值')

对于选择框 : 单选 多选 下拉选择
设置选中的值需要放在数组中 : 
    $(':radio').val([1])
    $(':radio').val([1,2,3])
对于选择框,设置值放在数组中:val([])

3.6 css样式

$('div').css('background-color','red')           //设置一个样式
$('div').css({'height':'100px','width':'100px'}) //设置多个样式
jq对象.css()

 

4.jquery两种扩展方法

<script> 
      $.extend({
        print1:function(name){            //print1是自己定义的函数名字,括号中的name是参数
            console.log(name)
        }
    });
     $.print1("") ;                           //调用时直接$.函数名(参数);
</script>     
1.类方法($.extend())
<body>
    <input type="text">
    <script>
            $.fn.extend({
            getMax:function(a,b){
                var result=a>b?a:b;
                console.log(result);
            }
        });
        $("input").getMax(1,2);        //调用时要$(标签名).函数名();
    </script>
</body>
2.对象方法($.fn.extend())

一般情况下,jQuery的扩展方法写在自执行匿名函数中(原因:在js中是以函数为作用域的,在函数中写可以避免自己定义的函数或者变量与外部冲突)

<script>
    (function(){
        $.extent({
            print1:function(){
            console.log(123);
            }
        })
    })();
</script>     
..

 

5.jquery绑定事件

js中绑定事件一般通过=赋值,jquery中一般通过方法。

<div class="div1">div1</div>
<script>
    $(".div1").click(function(){
        alert(this.innerText);
    })
    // $(".div1").click({"a":"b"},function(e){
    //     alert(e.data.a);
    // })
</script>
在script标签中绑定,传参用e.data接受
<ul id="ul1">
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>
<input type="button" value="+" class="input">
<script>
    $("#ul1 li").bind("click",function(){
        alert(123);
    });
    $(".input").bind("click",function(){
       $("#ul1").append("<li>555</li>");
    });
</script>
绑定事件二:bind bind绑定的事件对动态添加的标签没有用(点击新添加的li标签不会弹出“123”窗口)
<ul id="ul1">
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>
<input type="button" value="+" class="input">
<script>
    $("#ul1").on("click","li",function(){            //实现对ul1的委托li
        alert(123);
    });
    $(".input").bind("click",function(){
       $("#ul1").append("<li>555</li>");
    });
</script>
</body>
</html>
绑定事件三:on(有效解决了bind中的问题:动态添加的li标签点击后也能弹出“123”窗口)

事件举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../练习/jquery-3.4.1.min.js"></script>
</head>
<body>
    <div>
        <select name="s1" id="s1">
            <option value="nnnn">11</option>
            <option value="2">22</option>
            <option value="3">33</option>
            <option value="4">44</option>
            <option value="5">55</option>
        </select>
    </div>
</body>
<script>
    $("#s1").change(function () {
       alert($("#s1").select().val());
    });
</script>
</html>
select的change事件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #father{
            background-color: #2aabd2;
            width: 400px;
            height: 400px;
        }
        #son{
            background-color: #8c222c;
            width: 100px;
            height: 100px;
        }
    </style>
    <script src="../练习/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>
    <div id="father">
        <div id="son"></div>
    </div>
</div>
<script>
    $("#father").bind("mouseover",fun);
    function fun() {
        console.log("23");
    }
</script>
</body>
</html>
mouseover/mouseout事件(鼠标移动到父元素中的子元素上也会触发事件)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #father{
            background-color: #2aabd2;
            width: 400px;
            height: 400px;
        }
        #son{
            background-color: #8c222c;
            width: 100px;
            height: 100px;
        }
    </style>
    <script src="../练习/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>
    <div id="father">
        <div id="son"></div>
    </div>
</div>
<script>
    $("#father").bind("mouseenter",fun);
    function fun() {
        console.log("23");
    }
</script>
</body>
</html>
mouseenter/mouseleave=hover事件(鼠标移动到父元素中的子元素上不会触发事件)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0,0,0,0.5);
            z-index: 9;
            display: none;
        }
        #div2{
            position: fixed;
            width: 400px;
            height: 400px;
            top: 50%;
            left: 50%;
            right: 0;
            bottom: 0;
            margin-left: -200px;
            margin-top: -200px;
            background-color: rgba(255,255,255,0.9);
            z-index: 9;
            display: none;
        }
    </style>
    <script src="../练习2/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>
    <button id="add_person">添加</button>
    <table border="1" cellpadding="10" id="table">
            <thead>
            <tr>
                <th>#</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>alex</td>
                    <td>10</td>
                    <td><button class="del">删除</button></td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>egon</td>
                    <td>20</td>
                    <td><button class="del">删除</button></td>
                </tr>
            </tbody>
    </table>
    <div id="div1"></div>
    <div id="div2">
        <p><label>姓名:<input type="text"></label></p>
        <p><label>年龄:<input type="text"></label></p>
        <p><label><input type="submit" id="submit"></label></p>
    </div>
</div>
<script>
    $("#add_person").bind("click",fun);
    function fun() {
        $("#div1").css("display","block");
        $("#div2").css("display","block");
    }
    $("tbody").on("click",".del",function () {   //在此处委托事件,点击事件是绑在父元素身上的
       $(this).parent().parent().remove()
    });

    $("#submit").bind("click",fun2);
    function fun2() {
        tr_dom = document.createElement("tr");
        tr_dom.innerHTML =
            '<td><input type="checkbox"></td>' +
            '<td>egon</td>' +
            '<td>20</td>' +
            '<td><button class="del">删除</button></td>';
        $("tbody").append(tr_dom);
        $("#div1").css("display","none");
        $("#div2").css("display","none");
    }
</script>
</body>
</html>
委托事件on,如果新添加的元素想要保有事件,就要给其父元素绑定事件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../练习2/jquery-3.4.1.min.js"></script>
</head>
<body>
<table border="1" cellspacing="10" cellpadding="10">
    <tr>
        <th>主机名</th>
        <th>IP</th>
        <th>详情</th>
    </tr>
    <tr>
        <td>localhost</td>
        <td>127.0.0.1</td>
        <td>
            <a href="test.html">点击</a>
        </td>
    </tr>
</table>
<script>
    $("tr").each(function (ind,dom) {
        $(this).click(function () {
            console.log(dom);
        })
    })
</script>
</body>
</html>
$("tr").each(function(ind,dom){jq代码}) ind为each遍历的下标,dom为dom对象

 

6.ready入口函数

6.1 jquery和js入口函数的区别

jQuery入口函数与js入口函数的区别:

区别一:书写个数不同:

Js 的入口函数只能出现一次,出现多次会存在事件覆盖的问题。

jQuery 的入口函数,可以出现任意多次,并不存在事件覆盖问题。

区别二:执行时机不同:

Js的入口函数是在所有的文件资源加载完成后,才执行。这些文件资源包括:页面文档、外部的js文件、外部的css文件、图片等。

jQuery的入口函数,是在文档加载完成后,就执行。文档加载完成指的是:DOM树加载完成后,就可以操作DOM了,不用等到所有的外部资源都加载完成。

文档加载的顺序:从上往下,边解析边执行。
区别

6.2 jquery入口函数写法

$(document).ready(function () {
           alert(1);
       })
写法一:文档加载完毕,图片不加载的时候
$(function () {
           alert(1);
       });
写法二:文档加载完毕,图片不加载的时候
$(window).ready(function () {
           alert(1);
       })
写法三:文档加载完毕,图片也加载完毕的时候

7.事件冒泡

事件冒泡指的就是在点击子元素后,子元素触发事件,而后父元素也会触发相应的事件。

<style>
        .outer{
            width: 300px;
            height: 300px;
            background-color: red;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: forestgreen;
        }
    </style>

<body>
    <div class="outer">
        <div class="inner"></div>
    </div>
</body>

<script>
    $('.outer').click(
        function () {
            alert('outer')
        }
    )
    $('.inner').click(
        function (e) {
            alert('inner')
            // e.stopPropagation() //阻止事件冒泡方法1
            return false    //阻止事件冒泡方法2
        }
    )
</script>
事件冒泡(阻止事件冒泡方法1.e.stopPropagation() 2.return false)

8.动画

$('div').show(3000);
$("div").show("slow");

//show(毫秒值,回调函数;
    $("div").show(5000,function () {
        alert("动画执行完毕!");
    });
show动画
$('#box').toggle(3000,function(){});
toggle动画
$(selector).slideDown(speed, 回调函数);
$(selector).slideUp(speed, 回调函数);
$(selector).slideToggle(speed, 回调函数);
滑入滑出(slideUp)
 $(selector).fadeIn(speed, callback);
$(selector).fadeOut(1000);
 $(selector).fadeToggle('fast', callback);
淡入淡出(fadeIn)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container{
            width: 200px;
            height: 100px;
            position: relative;
            float: right;
        }
        .car{
            width: 100px;
            height: 40px;
            background-color: gray;
            text-align: center;
            line-height: 40px;
            position: absolute;
            right: 0;
        }
        .box{
            width: 200px;
            height: 200px;
            background-color: #2aabd2;
            position: absolute;
            top: 40px;
            display: none;
        }
    </style>
    <script src="../练习2/jquery-3.4.1.min.js"></script>
</head>
<body style="margin: 0">
<div class="container">
    <div class="car">购物车(<span>0</span>)</div>
    <div class="box"></div>
</div>
<script>
    $(".container").hover(function () {
        $(".box").stop();    //关闭之前的动画
        $(".box").slideToggle(1000);
    });

</script>
</body>
</html>
每次开启动画之前,先关闭之前的动画

 

三.js、jquery注意点

1.val()、value、valueof()

1.value是标签的属性值
<input type="text" value="sss">

2.val()是jQuery方法,如:$("input:text").val(),或$("input:text").val("demo");

3.valueof是js对象的方法,如
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var v=fruits.valueOf();
val()、value、valueof()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red{
            color: red;
        }
        #divs{
            width: 200px;
            height: 200px;
            background-color: #0000FF;
            display: none;
        }
    </style>
    <script src="../练习2/jquery-3.4.1.min.js"></script>
</head>
<body>
<button onclick="fun()">fds</button>
<div id="divs">
    <div id="div1">
        <p>1111</p>
        <p>2222</p>
        <p>3333</p>
    </div>
</div>
<script>
    var isShow = false;
    function fun() {
        $("#divs").toggle(3000);
        // if(!isShow){
        //     $("#divs").show(3000);
        //     isShow = true;
        // }else {
        //     $("#divs").hide("slow");
        //     isShow = false;
        // }
    }

</script>
</body>
</html>
toggle() 相当于hide、show两个事件

 

posted @ 2018-04-13 20:07  MISF  阅读(382)  评论(0编辑  收藏  举报
     JS过度和变形效果演示   
  
    html5.png