您的位置:首页 > Web前端 > JQuery

jQuery框架-1.jQuery基础知识

2019-10-26 13:12 1441 查看
原文链接:https://www.mk2048.com/blog/blog.php?id=h02ijicbahaa&title=jQuery%E6%A1%86%E6%9E%B6-1.jQuery%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86

jQuery简介

jQuery,顾名思义是JavaScript和查询(Query),jQuery是免费、开源的。它可以简化查询DOM对象、处理事件、制作动画、处理Ajax交互过程且兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多)。

jQuery优势

  1. 体积小,使用灵巧(只需引入一个js文件)。
  2. 方便的选择页面元素(模仿CSS选择器更精确、灵活)。
  3. 动态更改页面样式/页面内容(操作DOM,动态添加、移除样式)。
  4. 控制响应事件(动态添加响应事件)。
  5. 提供基本网页特效(提供已封装的网页特效方法)。
  6. 快速实现通信(ajax)。
  7. 易扩展、插件丰富。
  8. 支持链式写法。

引入jQuery

  1. 通过script引入本地jQuery文件。
  2. 通过引入CDN上面jQuery文件。

版本选择

  • 1.x:兼容ie678,使用最为广泛的,官方只做BUG维护,功能不再新增。因此一般项目来说,使用1.x版本就可以了,最终版本:1.12.4 (2016年5月20日)
  • 2.x:不兼容ie678,很少有人使用,官方只做BUG维护,功能不再新增。如果不考虑兼容低版本的浏览器可以使用2.x,最终版本:2.2.4 (2016年5月20日)
  • 3.x:不兼容ie678,只支持最新的浏览器。除非特殊要求,一般不会使用3.x版本的,很多老的jQuery插件不支持这个版本。目前该版本是官方主要更新维护的版本。

jQuery和$的关系:

一、jQuery选择器

  •  ID选择器:$(“#box”);
  • 类名选择器:$(“.box”);
  • 标签选择器:$(“div”);
  • 后代选择器:$(“#box  p”);
  • :first:获取第一个元素。
  • :last:获取最后一个元素。
  • :even:匹配所有索引值为偶数的元素,从 0 开始计数。
  • :odd:匹配所有索引值为奇数的元素,从 0 开始计数。
  • :eq(index):匹配一个给定索引值的元素,从 0 开始计数。
  • :not(selector):去除所有与给定选择器匹配的元素。
  • :has(selector):匹配含有选择器所匹配的元素的元素。 
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>jQuery练习</title>
</head>
<body>
<ul id="list">
<li class="special"><span>测试数据</span></li>
<li>测试数据</li>
<li>测试数据</li>
<li>测试数据</li>
<li class="special"><span>测试数据</span></li>
</ul>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
$('#list').css('list-style','none');
$('#list').css('background','#555555');
$('#list li').css('height',30);
/*多属性设置以对象的方式进行传参*/
$('ul li').css({
/*设置css属性line-height必须加单位*/
'line-height':'30px',
'width':'80%',
'opacity':.8,
'margin':'10px auto',
'background':'#f4f4f4'
});
/*eq获取设置对应下标元素*/
$('ul li:eq(1)').css('color','#ff0000');
/*实现隔行换色*/
$('ul li:odd').css('background','#888888');
$('ul li:even').css('background','#333333');
/*分别获取第一个和最后一个元素*/
$('ul li:first').css('background','#ff0000');
$('ul li:last').css('background','#ff0000');
/*适用去除选择器的元素*/
$('ul li:not(.special)').css('color','orange')
/*适用满足选择器元素的子元素*/
$('ul li:has(span)').css('color','purple')

</script>
</html>

二、jQuery属性和样式CSS

操作属性:

attr(name|properties|key,value|fn):设置或返回被选元素的属性值。

removeAttr(name):从每一个匹配的元素中删除一个属性。

prop(name|properties|key,value|fn):获取在匹配的元素集中的第一个元素的属性值。

removeProp(name):用来删除由.prop()方法设置的属性集。

区别:attr可以操作(增删改查)自定义的节点属性,而prop不可以(增删改查)。attr和prop对input的disabled属性的返回值不一致,attr返回disabled或者undefined,而prop返回布尔值。 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
body{
position:relative;
overflow: hidden;
}
.container{
height:200px;
background:#ff0000;
line-height: 200px;
text-align: center;
color: #ffffff;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
</style>
</head>
<body>
<div class="container" data-save="data">
<div class="box">
输入内容:<input class="test"  type="text" disabled/>
</div>
</div>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
//    操作属性
//    读取属性值
console.log($('[type=text]').attr('class'));
console.log($('[type=text]').prop('class'));
console.log($('[type=text]').attr('name'));//返回undefined
console.log($('[type=text]').prop('name'));//无返回值

console.log($('[type=text]').attr('disabled'));    //返回值disabled
console.log($('[type=text]').prop('disabled')); //返回值true
//    attr支持所有属性节点的增删改 prop支持自带属性的操作,不支持自定义属性的操作
//    操作标签自带属性
$('.container').attr('class','boxcontainer')    //设置class属性为boxcontainer
$('.box').prop('class','containerClass')    //设置class属性为containerClass
//    操作标签自定义属性
$('.containerClass').attr('data-save','update')    //成功更改
$('.boxcontainer').prop('data-save','update') //不起作用
//    删除相关属性removeAttr移除相关属性 removeProp移除相关属性值且赋值undefined
$('.containerClass').removeAttr("class")
$('.boxcontainer').removeProp("class")
</script>
</html>

 操作Class:

addClass(class|fn) :为每个匹配的元素添加指定的类名。

removeClass([class|fn]) :从所有匹配的元素中删除全部或者指定的类。

toggleClass(class|fn[,switch]):如果存在(不存在)就删除(添加)一个类。 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
body{
position:relative;
overflow: hidden;
}
.container{
width:100px;
height:100px;
background:#ff0000;
line-height: 100px;
text-align: center;
color: #ffffff;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
.changeClass{
width:100px;
height:100px;
line-height: 100px;
text-align: center;
color: #ffffff;
background: #000000;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box toggleClassOne">
显示内容
</div>
</div>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
//    操作class
//    添加class
//    $('.container').addClass('changeClass');
//    移除class
//    $('.container').removeClass('changeClass');
//    链式写法与上面的分开效果同
$('.container').addClass('changeClass').removeClass('container');
//    toggleClass存在删除不存在添加
$('.box').toggleClass('toggleClassOne');
$('.box').toggleClass('toggleClassTwo');
</script>
</html>

 操作内容:

html([val|fn]):取得第一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。

text([val|fn]):取得所有匹配元素的内容。结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。

val([val|fn|arr]):获得匹配元素的当前值。如果多选,将返回一个数组,其包含所选的值。 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
ul{
list-style: none;
width: 50%;
margin: 0 auto;
text-align: center;
}
#list li{
line-height: 40px;
border-bottom: 1px dashed #ff0000;
font-size: 20px;
}
</style>
</head>
<body>
<div class="container" data-save="data">
<div class="box">
<ul id="list">
<li>这是1</li>
<li class="even">这是2</li>
<li>这是3</li>
</ul>
</div>
<input type="text" name="username" id="username"/>
<div class="testhtml">

</div>
<div class="testtext">

</div>
</div>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
//     操作内容
//html标签文本输出   text输出文本
console.log($('.container').html());
console.log($('.container').text());
//赋值时html标签可渲染  text当文本处理
$('.testhtml').html('<b>好诗!</b>');
$('.testtext').text('<b>好诗!</b>');
$('[name=username]').val('用户名');
console.log($('[name=username]').val());
</script>
</html>

 

操作CSS:

css(name|pro|[,val|fn]):访问匹配元素的样式属性。

 

// 操作样式(详细请查看选择器)
console.log($('#box').css('width'));
$('#box').css({'width': 250, height: 500});

 操作位置:

offset([coordinates]):获取匹配元素在当前文档的相对偏移。返回的对象包含两个整型属性:top 和 left,以像素计。方法只对可见元素有效。

position():获取匹配元素相对父元素的偏移。返回的对象包含两个整型属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。

scrollTop([val]):获取匹配元素相对滚动条顶部的偏移。此方法对可见和隐藏元素均有效。

scrollLeft([val]):获取匹配元素相对滚动条左侧的偏移。此方法对可见和隐藏元素均有效。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
body{
position: relative;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background: #ff0000;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
.box{
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
color: #ffffff;
background: #000000;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="container" data-save="data">
<div class="box">
中心
</div>
</div>

<div id="outer" style="width: 200px; height: 200px; overflow: auto;
border: 1px solid #ccc; padding: 10px; margin: 10px;">
<div id="inner" style="height: 400px;"></div>
</div>

</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
//获取相对于文档的left和top的值
console.log($('.container').offset())
//设置left和top值
$('.box').offset({left:0,top:0})
console.log($('.box').offset())
console.log($('#outer').scrollTop());
$('#outer').scrollTop(50);
$('#outer').scroll(function () {
console.log($('#outer').scrollTop());
});
</script>
</html>

 操作尺寸:

height([val|fn]):取得匹配元素当前计算的高度值(px)。

width([val|fn]):取得第一个匹配元素当前计算的宽度值(px)。

innerHeight():获取第一个匹配元素内部区域高度(包括补白、不包括边框)。此方法对可见和隐藏元素均有效。

innerWidth():获取第一个匹配元素内部区域宽度(包括补白、不包括边框)。此方法对可见和隐藏元素均有效。

outerHeight([options]):获取第一个匹配元素外部高度(默认包括补白和边框)。此方法对可见和隐藏元素均有效。

outerWidth([options]):获取第一个匹配元素外部宽度(默认包括补白和边框)。此方法对可见和隐藏元素均有效。

注:设置options为true,计算margin在内。 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
</style>
</head>
<body>
<div id="outer" style="width: 200px; height: 200px; overflow: auto; border: 1px solid #ccc; padding: 10px; margin: 10px;">
<div id="inner" style="height: 400px;"></div>
</div>

</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
console.log($('#outer').width(150));
console.log($('#outer').height(130));
// 补白的宽度、高度
console.log($('#outer').innerWidth());
console.log($('#outer').innerHeight());
// 边框和补白的宽度、高度
console.log($('#outer').outerWidth());
console.log($('#outer').outerHeight());
// 外边距、边框和补白的宽度、高度
console.log($('#outer').outerWidth(true));
console.log($('#outer').outerHeight(true));
</script>
</html>

 三、过滤查找 

过滤元素:(与选择器的作用基本相同,只是分装成方法使用,此处不再举例)

eq(index|-index):获取第N个元素。这个元素的位置是从0算起,如果是负数,则从集合中的最后一个元素开始倒数。

first():获取第一个元素。

last():获取最后一个元素。

hasClass(class):检查当前的元素是否含有某个特定的类,如果有,则返回true。

has(expr|ele):保留包含特定后代的元素,去掉那些不含有指定后代的元素。

not(expr|ele|fn):删除与指定表达式匹配的元素。

查找元素:

children([expr]):取得一个包含匹配的元素集合中每一个元素的所有子元素的元素集合。只考虑子元素而不考虑所有后代元素。

find(expr|obj|ele):搜索所有与指定表达式匹配的子元素。

parent([expr]):取得一个包含着所有匹配元素的唯一父元素的元素集合。

offsetParent():返回第一个匹配元素用于定位的父节点。

next([expr]):取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。

nextAll([expr]):查找当前元素之后所有的同辈元素。

prev([expr]):取得一个包含匹配的元素集合中每一个元素紧邻的前一个同辈元素的元素集合。

prevAll([expr]):查找当前元素之前所有的同辈元素。

siblings([expr]):取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。可以用可选的表达式进行筛选。

串联操作:

add(expr|ele|html|obj[,con]):把与表达式匹配的元素添加到jQuery对象中。这个函数可以用于连接分别与两个表达式匹配的元素结果集。返回的结果将始终以元素在HTML文档中出现的顺序来排序,而不再是简单的添加。

 

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>jQuery练习-选择器</title>
</head>
<body>
<ul id="list">
<li><label>测试数据</label></li>
<li>测试数据</li>
<li class="special">测试数据</li>
<li>测试数据</li>
</ul>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
$('#list .special').add('label').css('background','#ff0000');
</script>
</html>

 

andSelf():将先前所选的加入当前元素中。

 

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>jQuery练习-选择器</title>
</head>
<body>
<ul id="list">
<li>测试数据</li>
<li>测试数据</li>
<li class="special">测试数据</li>
<li>测试数据</li>
</ul>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
$('#list .special').nextAll().andSelf().css('background','#ff0000');
</script>
</html>

 end():回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。如果之前没有破坏性操作,则返回一个空集。所谓的"破坏性"就是指任何改变所匹配的jQuery元素的操作。

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>jQuery练习-end()</title>
</head>
<body>
<ul class="first">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
<ul class="second">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script>
//end() 方法结束当前链条中的最近的筛选操作,并将匹配元素集还原为之前的状态
$('ul.first').find('.foo').css('background-color', 'red')
.end().find('.bar').css('background-color', 'green');
</script>
</html>

四、jQuery事件 

页面载入事件:

ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。简单地说,这个方法纯粹是对向window.load事件注册事件的替代方法。 

/*DOMContenLoaded:dom结构加载完成后调用事件;
load:dom结构加载完成后链接的资源加载完成后执行;
网页加载的内容越大,二者之间相差的时间越长,相对的DOMContentLoaded事件用户体验更合适*/
//ready()方法是在DOMContenLoaded方法上封装的
$(document).ready(function () {
console.log('页面加载完成!');
});
//此调用方式等同于使用ready事件,可查看jQuery源码
$(function () {
console.log('页面加载完成!');
});

 绑定事件:

参数说明:

  • [li]events:表示jQuery事件不加on,可同时绑定多个事件,事件间用空格隔开例如:'click dbclick';
  • [selector]:表示对应样式的选择器;
  • [data]:表示传入回调函数的参数,用event.data进行接收
  • fn:回调函数
[/li]

on(events,[selector],[data],fn):在选择元素上绑定一个或多个事件的事件处理函数。

off(events,[selector],[fn]):在选择元素上移除一个或多个事件的事件处理函数。

bind(type,[data],fn):为每个匹配元素的特定事件绑定事件处理函数。

unbind(type,[data|fn]]):bind()的反向操作,从每一个匹配的元素中删除绑定的事件。如果没有参数,则删除所有绑定的事件。

one(type,[data],fn):为每一个匹配元素的特定事件(像click)绑定一个一次性的事件处理函数。

hover([over,]out):当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。

click([[data],fn]):触发每一个匹配元素的click事件。这个函数会调用执行绑定到click事件的所有函数。

注:其他事件方法使用方式一样。例如:mouseover、mouseout、dblclick、change、blur、focus、keydown、keyup、keypress、mousedown、mouseup、mousemove、mouseenter、mouseleave、resize、scroll、select、submit、unload等。 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>属性和css</title>
<style type="text/css">
html,body{
height:100%;
}
ul{
list-style: none;
width: 50%;
margin: 0 auto;
text-align: center;
}
#list li{
line-height: 40px;
border-bottom: 1px dashed #ff0000;
font-size: 20px;
}
</style>
</head>
<body>
<div class="container" data-save="data">
<div class="box">
<ul id="list">
<li>这是1</li>
<li class="even">这是2</li>
<li>这是3</li>
<li>这是4</li>
<li>这是5</li>
<li class="even">这是6</li>
<li>这是7</li>
<li>这是8</li>
</ul>
</div>
</div>
</body>
<!--考虑兼容选择相应的版本,此处参考百度选择1.x的版本进行说明,案例不提供此文件自行下载-->
<script type="text/javascript" src="js/jquery.1.8.3.js"></script>
<script type="text/javascript">
/*    //添加单击事件
$('#list li').on('click',function(){
alert(this.innerHTML);
})*/

/*    //添加双击事件
$('#list li').on('dblclick',function(){
alert(this.innerHTML);
})
//无法移除双击事件(不是同一个方法)
$('#list li').off('dblclick',function(){
alert(this.innerHTML);
})*/
function fun(){
alert(0000);
}

/*    //添加双击事件且可选择选择器过滤
$('#list').on('dblclick','.even',fun);
//可移除双击事件
$('#list').off('dblclick',fun);*/

/*    //添加双击事件
$('#list').on('dblclick',fun);
//无法移除双击事件与添加双击事件的方法选择器对应或者全部移除
$('#list').off('dblclick','.even',fun);*/

/*    //bind和on的区别是其无法进行选择器过滤,其他用法基本相同都可添加多个事件
$('#list').bind('click ', fun);
$('#list').unbind('click', fun);*/

/*    //一次性事件处理函数
$('#list').one('click',{'param':'参数'},function(e){
console.log(e.data['param'])
})*/

/*
//鼠标划入划出事件
$('#list').hover(function(){
console.log("鼠标划入")
},
function(){
console.log("鼠标划出")
})*/

$('#list').click(function(){
console.log("鼠标点击事件")
})
</script>
</html>

附录:

选项卡实例demo: 

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery选项卡效果</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
html,body{
height: 100%;
}
body{
background: #f4f4f4;
}
ul{
list-style: none;
}
.container{
width: 600px;
margin: 100px auto;
background: #ffffff;
border-radius: 10px;
border:1px solid #555555;
overflow: hidden;
}
.header-box{

}
.tab-navigation{
overflow: hidden;
background: #eeeeee;
color: #080808;
border-bottom: 1px solid #555555;
}
.tab-navigation li{
float: left;
width: 100px;
text-align: center;
line-height: 50px;
}
.tab-body{
width: 100%;
height: 300px;
position: relative;
}
.tab-body li{
padding: 10px;
position: absolute;
left: 0;
top: 0;
}
.tab-body li:first-child{
display: block;
}
.tab-body li:nth-child(n 2){
display: none;
}
.tab-navigation .selected{
background: #ffffff;
color: #000000;
}
.tab-navigation .active{
background: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="header-box">
<ul class="tab-navigation">
<li class="selected">选项卡1</li>
<li>选项卡2</li>
<li>选项卡3</li>
<li>选项卡4</li>
<li>选项卡5</li>
<li>选项卡6</li>
</ul>
</div>
<div class="body-box">
<ul class="tab-body">
<li>内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1</li>
<li>内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2</li>
<li>内容3内容3内容3内容3内容3内容3内容3内容3内容3内容3内容3</li>
<li>内容4内容4内容4内容4内容4内容4内容4内容4内容4内容4内容4</li>
<li>内容5内容5内容5内容5内容5内容5内容5内容5内容5内容5内容5</li>
<li>内容6内容6内容6内容6内容6内容6内容6内容6内容6内容6内容6</li>
</ul>
</div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript">
$('.tab-navigation li').click(function () {
$(this).addClass('selected').siblings().removeClass('selected')
var index = $('.tab-navigation li').index(this);
$('.tab-body li').eq(index).css('display','block').siblings().css('display','none');
}).hover(function () {
$(this).addClass('active');
},function () {
$(this).removeClass('active');
});
</script>
</html>

 


更多专业前端知识,请上【猿2048】www.mk2048.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: