JQuery

一、jQuery简单介绍

jQuery它是一个轻量级的、兼容多浏览器的JavaScript库。

优点:

- 是一款轻量级的JS框架,不会影响页面加载速度

- 丰富的DOM选择器,jQuery的选择器用起来更方便

- 链式表达式,可以把多个操作写在一行代码里,更加简洁

- 事件、样式、动画支持

- Ajax操作支持

- 跨浏览器兼容

- 插件扩展开发,拥有者丰富的第三方插件

二、jQuery基础语法

1.查找标签

基本选择器

id选择器:$("#id")

标签选择器:$("tagName")

class选择器:$(".className")

混合使用:$("div.c1")  // 找到有c1 class类的div标签

所有元素选择器:$("*")

组合选择器:$("#id, .className, tagName")

层级选择器

$("x y");// x的所有后代y(子子孙孙)
$("x > y");// x的所有儿子y(儿子)
$("x + y")// 找到所有紧挨在x后面的y
$("x ~ y")// x之后所有的兄弟y

基本筛选器

:first // 第一个
:last // 最后一个
:eq(index)// 索引等于index的那个元素
:even // 匹配所有索引值为偶数的元素,从 0 开始计数
:odd // 匹配所有索引值为奇数的元素,从 0 开始计数
:gt(index)// 匹配所有大于给定索引值的元素
:lt(index)// 匹配所有小于给定索引值的元素
:not(元素选择器)// 移除所有满足not条件的标签
:has(元素选择器)// 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)

练习:自定义模态框,使用jQuery实现弹出和隐藏功能

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>自定义模态框</title>
  <style>
    .cover {
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background-color: darkgrey;
      z-index: 999;
    }
    .modal {
       600px;
      height: 400px;
      background-color: white;
      position: fixed;
      left: 50%;
      top: 50%;
      margin-left: -300px;
      margin-top: -200px;
      z-index: 1000;
    }
    .hide {
      display: none;
    }
  </style>
</head>
<body>
<input type="button" value="弹" id="i0">

<div class="cover hide"></div>
<div class="modal hide">
  <label for="i1">姓名</label>
  <input id="i1" type="text">
   <label for="i2">爱好</label>
  <input id="i2" type="text">
  <input type="button" id="i3" value="关闭">
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  var tButton = $("#i0")[0];
  tButton.onclick=function () {
    var coverEle = $(".cover")[0];
    var modalEle = $(".modal")[0];

    $(coverEle).removeClass("hide");
    $(modalEle).removeClass("hide");
  };

  var cButton = $("#i3")[0];
  cButton.onclick=function () {
    var coverEle = $(".cover")[0];
    var modalEle = $(".modal")[0];

    $(coverEle).addClass("hide");
    $(modalEle).addClass("hide");
  }
</script>
</body>
</html>

jQuery版自定义模态框
自定义模态框

属性选择器

<input type="text">
<input type="password">
<input type="checkbox">
$("input[type='checkbox']");// 取到checkbox类型的input标签
$("input[type!='text']");// 取到类型不是text的input标签

表单选择器

:+ 表单对象属性

$(":checkbox")  // 找到所有的checkbox
<select id="s1">
  <option value="beijing">北京市</option>
  <option value="shanghai">上海市</option>
  <option selected value="guangzhou">广州市</option>
  <option value="shenzhen">深圳市</option>
</select>

$(":selected")  // 找到所有被选中的option

2.筛选器方法

下一个元素

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")

上一个元素

$("#id").prev()
$("#id").prevAll()
$("#id").prevUntil("#i2")

父亲元素

$("#id").parent()
$("#id").parents()  // 查找当前元素的所有的父辈元素
$("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。

儿子和兄弟元素

$("#id").children();// 儿子们
$("#id").siblings();// 兄弟们

查找元素

$("div").find("p")  <==>  $("div p")

筛选

$("div").filter(".c1")  <==>  $("div.c1")

.first() // 获取匹配的第一个元素
.last() // 获取匹配的最后一个元素
.not() // 从匹配元素的集合中删除与指定表达式匹配的元素
.has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
.eq() // 索引值等于指定值的元素

示例:左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>左侧菜单示例</title>
  <style>
    .left {
      position: fixed;
      left: 0;
      top: 0;
       20%;
      height: 100%;
      background-color: rgb(47, 53, 61);
    }

    .right {
       80%;
      height: 100%;
    }

    .menu {
      color: white;
    }

    .title {
      text-align: center;
      padding: 10px 15px;
      border-bottom: 1px solid #23282e;
    }

    .items {
      background-color: #181c20;

    }
    .item {
      padding: 5px 10px;
      border-bottom: 1px solid #23282e;
    }

    .hide {
      display: none;
    }
  </style>
</head>
<body>

<div class="left">
  <div class="menu">
    <div class="item">
      <div class="title">菜单一</div>
      <div class="items">
        <div class="item">111</div>
        <div class="item">222</div>
        <div class="item">333</div>
    </div>
    </div>
    <div class="item">
      <div class="title">菜单二</div>
      <div class="items hide">
      <div class="item">111</div>
      <div class="item">222</div>
      <div class="item">333</div>
    </div>
    </div>
    <div class="item">
      <div class="title">菜单三</div>
      <div class="items hide">
      <div class="item">111</div>
      <div class="item">222</div>
      <div class="item">333</div>
    </div>
    </div>
  </div>
</div>
<div class="right"></div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

<script>
  $(".title").click(function (){  // jQuery绑定事件
    // 隐藏所有class里有.items的标签
    // $(".items").addClass("hide");  //批量操作
    // $(this).next().removeClass("hide");
    
    // jQuery链式操作
    $(this).next().removeClass('hide').parent().siblings().find('.items').addClass('hide')
  });
</script>
左侧菜单

3.操作标签

样式操作

addClass();// 添加指定的CSS类名。
removeClass();// 移除指定的CSS类名。
hasClass();// 判断样式存不存在
toggleClass();// 切换CSS类名,如果有就移除,如果没有就添加。

位置操作

offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置
position()// 获取匹配元素相对父元素的偏移
scrollTop()// 获取匹配元素相对滚动条顶部的偏移
scrollLeft()// 获取匹配元素相对滚动条左侧的偏移

尺寸

height()
width()
innerHeight()
innerWidth()
outerHeight()
outerWidth()

文本操作

html()// 取得第一个匹配元素的html内容
html(val)// 设置所有匹配元素的html内容

text()// 取得所有匹配元素的内容
text(val)// 设置所有匹配元素的内容

val()// 取得第一个匹配元素的当前值
val(val)// 设置所有匹配元素的值
val([val1, val2])// 设置多选的checkbox、多选select的值

示例:自定义登录校验

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>文本操作之登录验证</title>
  <style>
    .error {
      color: red;
    }
  </style>
</head>
<body>

<form action="">
  <div>
    <label for="input-name">用户名</label>
    <input type="text" id="input-name" name="name">
    <span class="error"></span>
  </div>
  <div>
    <label for="input-password">密码</label>
    <input type="password" id="input-password" name="password">
    <span class="error"></span>
  </div>
  <div>
    <input type="button" id="btn" value="提交">
  </div>
</form>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  $("#btn").click(function () {
    var username = $("#input-name").val();
    var password = $("#input-password").val();

    if (username.length === 0) {
      $("#input-name").siblings(".error").text("用户名不能为空");
    }
    if (password.length === 0) {
      $("#input-password").siblings(".error").text("密码不能为空");
    }
  })
</script>
</body>
</html>

自定义登录校验示例
自定义登录校验

属性操作

用于ID等或自定义属性:

attr(attrName)// 返回第一个匹配元素的属性值
attr(attrName, attrValue)// 为所有匹配元素设置一个属性值
attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值
removeAttr()// 从每一个匹配的元素中删除一个属性

用于checkbox和radio

prop() // 获取属性
removeProp() // 移除属性

prop与attr的区别:

  虽然都是属性,但他们所指的属性并不相同,attr所指的属性是HTML标签属性,而prop所指的是DOM对象属性,可以认为attr是显式的,而prop是隐式的。

  attr获取一个标签内没有的东西会得到undefined,而prop获取的是这个DOM对象的属性,因此checked为false。

  attr用范围只限于HTML标签内的属性,而prop获取的是这个DOM对象的属性

  prop不支持获取标签的自定义属性

小结:

  - 对于标签上有的能看到的属性和自定义属性都用attr

  - 对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop

文档处理

添加到指定元素内部的后面

$(A).append(B)// 把B追加到A
$(A).appendTo(B)// 把A追加到B

添加到指定元素内部的前面

$(A).prepend(B)// 把B前置到A
$(A).prependTo(B)// 把A前置到B

添加到指定元素外部的后面

$(A).after(B)// 把B放到A的后面
$(A).insertAfter(B)// 把A放到B的后面

添加到指定元素外部的前面

$(A).before(B)// 把B放到A的前面
$(A).insertBefore(B)// 把A放到B的前面

移除和清空元素

remove()// 从DOM中删除所有匹配的元素。
empty()// 删除匹配的元素集合中所有的子节点。

克隆示例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>克隆</title>
  <style>
    #b1 {
      background-color: deeppink;
      padding: 5px;
      color: white;
      margin: 5px;
    }
    #b2 {
      background-color: dodgerblue;
      padding: 5px;
      color: white;
      margin: 5px;
    }
  </style>
</head>
<body>

<button id="b1">屠龙宝刀,点击就送</button>
<hr>
<button id="b2">屠龙宝刀,点击就送</button>

<script src="jquery-3.2.1.min.js"></script>
<script>
  // clone方法不加参数true,克隆标签但不克隆标签带的事件
  $("#b1").on("click", function () {
    $(this).clone().insertAfter(this);
  });
  // clone方法加参数true,克隆标签并且克隆标签带的事件
  $("#b2").on("click", function () {
    $(this).clone(true).insertAfter(this);
  });
</script>
</body>
</html>
克隆

4.事件

常用事件

click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})

事件绑定

.on( events [, selector ],function(){})

even:事件

selector:选择器

function:事件处理函数

移除事件

.off( events [, selector ][,function(){}])

阻止后续事件执行

  return false; // 常见阻止表单提交等

  e.preventDefault()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阻止默认事件</title>
</head>
<body>

<form action="">
    <button id="b1">点我</button>
</form>

<script src="jquery-3.3.1.min.js"></script>
<script>
    $("#b1").click(function (e) {
        alert(123);
        //return false;
        e.preventDefault();
    });
</script>
</body>
</html>

阻止事件冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阻止事件冒泡</title>
</head>
<body>
<div>
    <p>
        <span>点我</span>
    </p>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
    $("span").click(function (e) {
        alert("span");
        e.stopPropagation();
    });

    $("p").click(function () {
        alert("p");
    });
    $("div").click(function () {
        alert("div");
    })
</script>
</body>
</html>

事件委托

事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件

$("table").on("click", ".delete", function () {
  // 删除按钮绑定的事件
})

5.动画效果

// 基本
show([s,[e],[fn]])
hide([s,[e],[fn]])
toggle([s],[e],[fn])
// 滑动
slideDown([s],[e],[fn])
slideUp([s,[e],[fn]])
slideToggle([s],[e],[fn])
// 淡入淡出
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn])
fadeTo([[s],o,[e],[fn]])
fadeToggle([s,[e],[fn]])

示例:点赞效果

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>点赞动画示例</title>
  <style>
    div {
      position: relative;
      display: inline-block;
    }
    div>i {
      display: inline-block;
      color: red;
      position: absolute;
      right: -16px;
      top: -5px;
      opacity: 1;
    }
  </style>
</head>
<body>

<div id="d1">点赞</div>
<script src="jquery-3.2.1.min.js"></script>
<script>
  $("#d1").on("click", function () {
    var newI = document.createElement("i");
    newI.innerText = "+1";
    $(this).append(newI);
    $(this).children("i").animate({
      opacity: 0
    }, 1000)
  })
</script>
</body>
</html>
点赞动画效果

each

遍历一个jQuery对象,为每个匹配元素执行一个函数

// 为每一个li标签添加foo
$("li").each(function(){
  $(this).addClass("c1");
});
原文地址:https://www.cnblogs.com/hexianshen/p/12125291.html