day57---jQuery

jQuery操作标签类

对比js

原生JavaScript操作标签 jQuery操作标签
classList.add() addClass()
classList.remove() removeClass()
classList.cantains() hasClass()
classList.toggle() toggleClass()

样式类

"""
addClass()    # 添加指定的css类名
removeClass() # 移除指定的css类名
hasClass()    # 判断样式存不存在
toggleClass() # 切换css类名,有就删除,如果没有就添加
"""

示例一:模态框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>模态框</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .cover {
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: darkgrey;
            z-index: 999;
        }

        .model {
             440px;
            height: 400px;
            background-color: white;
            position: fixed;
            left: 50%;
            top: 50%;
            margin-left: -220px;
            margin-top: -200px;
            z-index: 1000;
        }

        #d2 {
            color: blue;
            margin: 40px;
        }

        .c1 {
            margin: 10px;
        }

        span {
            font-size: 12px;
            color: red;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>
<input type="button" id="d1" value="注册">
<div class="cover hide"></div>
<div class="model hide">
    <div id="d2">
        <div class="c1">
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username" placeholder="请输入用户名~">
            <span></span>
        </div>
        <div class="c1">
            <label for="password">密&nbsp;&nbsp;&nbsp;码:</label>
            <input type="password" id="password" name="password" placeholder="请输入密码~">
            <span></span>
        </div>
        <input type="button" id="btn1" value="提交">&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="button" id="btn2" value="重置">
    </div>
</div>
<script>
    let $btnEle, $subEle, $resEle, $covEle, $modEle, $nameEle, $pwdEle;
    $btnEle = $('#d1');  //注册按钮
    $subEle = $('#btn1'); //提交按钮
    $resEle = $('#btn2'); //重置按钮
    $covEle = $('.cover');
    $modEle = $('.model');
    $btnEle.on('click', function () {
        $covEle.removeClass('hide');
        $modEle.removeClass('hide');
        $nameEle.val('');
        $pwdEle.val('');
    });
    // btn1功能按钮的实现
    $subEle.on('click', function () {
        $nameEle = $('#username');
        $pwdEle = $('#password');
        if (!$nameEle.val() && !$pwdEle.val()) {
            $nameEle.next().text('用户名不为空~');
            $pwdEle.next().text('密码不为空~');
        } else if (!$nameEle.val()) {
            $nameEle.next().text('用户名不为空~');
        } else if (!$pwdEle.val()) {
            $pwdEle.next().text('密码不为空~');
        } else {
            $covEle.addClass('hide');
            $modEle.addClass('hide');
        }
    });
    // btn2功能按钮的实现
    $resEle.on('click', function () {
        $nameEle = $('#username');
        $pwdEle = $('#password');
        $nameEle.val('').next().text('');
        $pwdEle.val('').next().text('');
    });
    //用户名密码框鼠标获取焦点,清空输入框后面的文本
    $('.c1>input').focus(function () {
        $(this).next().text('');
    });
</script>
</body>
</html>

CSS操作

jquery链式操作,类似于python中的链式操作,如下:

class Beast(object):
    def __init__(self,name):
        self.name = name
    
    def show(self):
        print(f'{self.name} is a beast!
')
        return self
    
    def choose(self):
        print(f'{self.name} is not a beast!
')
        return self
    
b = Beast('姜春')
b.show().choose()

姜春 is a beast!

姜春 is not a beast!

利用链式操作可以完成一个区域多个标签的属性值设置

<body>
<div id="d1">
    <p>O(∩_∩)O哈哈~</p>
    <p>(*^▽^*)</p>
</div>
<script>
    $('p').css('color','red').next().css('color','blue');
</script>
</body>

位置操作

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

示例:小火箭返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>小火箭返回顶部</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        #d1 {
            background-color: red;
             100%;
            height: 400px;
        }

        #d2 {
            background-color: green;
             100%;
            height: 400px;
        }

        #d3 {
            background-color: blue;
             100%;
            height: 300px;
        }

        .c1 {
            position: fixed;
            bottom: 10px;
            right: 10px;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
<div class=" c1">
    <img src="rocket.png" alt="" class="hide">
</div>
<script>
    let $imgEle = $('.c1>img');
    $(window).scroll(function () {
        if ($(window).scrollTop() > 300) {
            $imgEle.removeClass('hide');
        } else {
            $imgEle.addClass('hide');
        }
    });
    $imgEle.on('click', function () {
        $(window).scrollTop(0);
    })
</script>
</body>
</html>

尺寸

<style>
    #d1{
        padding: 2px 3px 4px 1px;
    }
</style>

let $pEle = $('#d1')

$pEle.width() //文本的宽度
1018
$pEle.height() //文本的高度
20.6667
$pEle.innerWidth() //文本的宽度+padding
1022
$pEle.innerHeight() //文本的高度+padding
26.6667
$pEle.outerWidth() //文本的宽度+padding+border
1022
$pEle.outerHeight() //文本的高度+padding+border
26.6667

文本操作

与js做对比

JavaScript操作 JQuery操作
文本值 innerText text()
HTML代码 innerHTML hmtl()
value val()
//获取文本值
$spanEle.text()
"O(∩_∩)O哈哈~" 
//设置文本值
$spanEle.text('o(* ̄︶ ̄*)o')

"""
等于js中的
let sEle = window.document.getElementById('d1');
sEle.innerText
//设置文本值
sEle.innerText = ‘o(* ̄︶ ̄*)o’;   
"""


//获取HTML代码
$spanEle.html()
"o(* ̄︶ ̄*)o"
//设置HTML代码
$spanEle.html('<u>(^o^)/</u>')

"""
等于js中的
sEle.innerHTML
"<u>(^o^)/</u>"
//设置HTML代码
sEle.innerText = ‘<i>(*^@^*)</i>’;   
"""

//获取值
let $iEle = $('#d2')
$iEle.val()
"enen"
//设置值
$iEle.val('你好呀')
    
"""
let iEle = window.document.getElementById('d2')
iEle.value
"你好呀"
//设置值
iEle.value = '好什么啊'
"好什么啊"
"""
    
//获取文件
let $fileEle = $('#d3')
$fileEle[0].files[0]  //将jQ对象转换为标签对象
File {name: "链式赋值.jpg", lastModified: 1589962292246, lastModifiedDate: Wed May 20 2020 16:11:32 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 7610, …}

属性操作

与js 做比较

javaScript操作 jQuery操作
设置属性 setAttribute() attr(name,value)
获取属性 getAttribute() attr(name)
移除属性 removeAttribute() removeAttr(name)
let $pEle = $('p')

$pEle.attr('class','c1') //设置class属性为c1

$pEle.attr('class') //查看class属性
"c1"

$pEle.removeAttr('class') //删除class属性


等于js中的:
"""
let pEle = window.document.getElementsByTagName('p')[0]
除了id是唯一的,其他拿到的全是数组,需要加索引取值
pEle.setAttribute('class','c1')

pEle.getAttribute('class')
"c1"

pEle.removeAttribute('class')
"""

注意:对于标签上能看到的属性和自定义属性用attr

返回布尔值比如checkbox radio option是否被选中用prop

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

prop和attr之间的区别

虽然都是属性,但他们所指的属性并不相同:
    (1)attr所指的属性是HTML标签属性;
    (3)prop所指的是DOM对象属性。
即 可以认为attr是显式的,而prop是隐式的。
$('#d2').prop('checked')
true
$('#d1').prop('checked')
false

$('#d4').prop('selected')
true

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

小节:

"""
(1)对于标签上有的能看到的属性和自定义属性都用attr;
(2)对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。
"""

文档处理

eg:

<body>
<p id="d2">O(∩_∩)O哈哈~</p>
<span>哦哦哦</span>
<div id="d1">
    <div>嗯嗯</div>
    <div>哈哈</div>
</div>
</body>
  • 添加到指定标签内部的尾部
let $pEle = $('#d2')
let $divEle = $('#d1')

$divEle.append($pEle) //在$divEle的尾部添加$pEle
$pEle.appendTo($divEle) //将$pEle添加到$divEle的尾部
  • 添加到指定标签内部的头部
$divEle.prepend($pEle) //在$divEle的头部添加$pEle
$pEle.prependTo($divEle) //将$pEle添加到$divEle的头部
  • 放在某个标签的后面
$pEle.after($divEle)  //在$pEle标签后面放置$divEle标签
$divEle.insertAfter($pEle) 
  • 放在某个标签前面
$pEle.before($divEle) //在$pEle标签前面放置$divEle标签
$divEle.insertBefore($pEle)
  • 将标签从DOM树中清除
$pEle.remove() //将$pEle标签从DOM树中删除
  • 清空标签内的所有内容
$divEle.empty() //删除匹配的元素集合中所有的子节点。

事件

jQuery绑定事件的两种方式

# 第一种
$(selector).click(function(){
    console.log($(this))
})
# 第二种
$(selector).on('click',function(){
    console.log($(this))
})

clone事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        #d1{
            height: 120px;
             120px;
            border-radius: 50%;
            border: 2px solid red;
            background-color: white;
            overflow: hidden;
            display: inline-block;
        }
    </style>
</head>
<body>
<div id="d1">
    <img src="blog_head.jpg" alt="宇智波鼬" title="宇智波鼬" width="100%">
</div>
<script>
    let $divEle = $('#d1');
    $divEle.on('click',function () {
        $(this).clone(true).insertAfter($('body'))
        // clone()方法默认只克隆html和css,不克隆事件;如果需要克隆事件,则将值设为true。此外this对象代表当前被点击的标签对象,通过$(this)将其装换为jQuery对象
    })
</script>
</body>
</html>

左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>菜单</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            margin: 0;
        }

        #d1 {
            height: 100%;
             24%;
            position: fixed;
            background-image: url("background-left.jpg");
        }

        .title {
            margin: 10px;
            border: 2px solid pink;
            text-align: center;
            color: white;
            font-size: 18px;
        }

        .hide {
            display: none;
        }

    </style>
</head>
<body>
<div id="d1">
    <div class="title">菜单一
        <div class="item">白暂鸡</div>
        <div class="item">烤肉</div>
        <div class="item">刀鱼</div>
    </div>
    <div class="title">菜单二
        <div class="item">日本豆腐</div>
        <div class="item">佛跳墙</div>
        <div class="item">三文鱼</div>
    </div>
    <div class="title">菜单三
        <div class="item">羊排</div>
        <div class="item">鲍鱼</div>
        <div class="item">帝王蟹</div>
    </div>
</div>
<script>
    $('.title').on('click',function () {
        $('.item').addClass('hide');
        $(this).children().removeClass('hide');
    })
</script>
</body>
</html>

input实时监控

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<input type="text" id="d1" placeholder="请输入用户名~"><br>
<textarea name="info" id="d2" class="hide" cols="30" rows="10"></textarea>
<script>
    $('#d1').on('input', function () {
        if (this.value) {
            $('#d2').removeClass('hide').val(this.value);
        }else{
            $('#d2').addClass('hide')
        }
    })
</script>
</body>
</html>

hover事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body{
            margin: 0;
        }
        #d1{
            height: 120px;
             120px;
            border: 2px solid red;
            background-color: white;
            border-radius:50%;
            overflow: hidden;
        }
    </style>
</head>
<body>
<div id="d1">
    <img src="blog_head.jpg" alt="" width="100%">
</div>
<script>
    $('#d1').hover(
        function () {
            alert('520快乐,大宝贝'); //鼠标悬浮
        },
        function () {
            alert('快乐毛线,你个单身狗!') //鼠标移开
        }
    )
</script>
</body>
</html>

键盘按下事件

<script>
    $(window).keydown(function (event) {
        console.log(event.keyCode)
        if (event.keyCode === 16){
            alert('你按了shift键')
        }
    })
</script>

阻止事件的继续运行

<body>
<div>
    <form action="">
        <p id="d2"></p>
        <input type="submit" value="提交" id="d1">
    </form>
</div>
<script>
    let $subEle = $('#d1');
    let $pEle = $('#d2');
    $subEle.on('click',function (event) {
        $pEle.text('宝贝,你还好吗');
        //阻止标签的后续所有事件的运行
        //return false
        //阻止标签的默认事件的运行
        event.preventDefault()
    })
</script>

阻止事件的冒泡

<div id="d1">我和你
    <div id="d2">心连心
        <a href="http://www.mzitu.com/" target="_blank" id="d3">福利链接1</a>
    </div>
    <span id="d4">别说了,你这个单身狗</span>
</div>
<script>
    let $divEle1,$divEle2,$aEle,$spanEle;
    $divEle1 = $('#d1');
    $divEle2 = $('#d2');
    $aEle = $('#d3');
    $spanEle = $('#d4');
    $divEle1.on('click',function () {
        alert('hello, div1!')
    });
    $divEle2.on('click',function () {
        alert('hello, div2!')
    });
    $aEle.on('click',function () {
        alert('hello, a!')
    });
    $spanEle.on('click',function (event) {
        alert('hello, span!');
        //阻止事件冒泡的方式1
        //return false
        //阻止事件的冒泡方式2
        event.stopPropagation()
    })

</script>

事件委托

let $butEle = $('<button>')

$butEle.text('无兄弟,不游戏')

$('body').append($butEle)

body>
<button >是兄弟,老婆我帮你照顾</button>
<script>
    // $('button').on('click',function () { //无法影响到动态创建的标签
    //     alert('去你的,滚蛋!')
    // })
    $('body').on('click','button',function () {
        alert('好的,她就交给你照顾了!')
    })
</script>
</body>

页面加载的几种方式

//等待页面加载完毕后再执行js代码
window.onload = function(){
    //js代码
}

"""jQuery中等待页面加载完毕"""
//第一种
$(document).ready(function(){
    //js代码
})

//第二种
$(function(){
    //js代码
})

//第三种
直接写在body的最下方

动画效果展示

    <style>
        #d1 {
             24%;
            height: 100%;
            position: fixed;
            background-image: url("background-left.jpg");
            border: 2px solid pink;
        }
    </style>

5秒后隐藏

<script>
    let $divEle = $('#d1');
    $divEle.hide(5000)
</script>

5秒后显示

$divEle.show(5000);

5秒后向上卷起来完毕

$divEle.slideUp(5000);

5秒后向下式展出来

$divEle.slideDown(5000);

5秒后渐变隐藏

$divEle.fadeOut(5000);

5秒后渐变出现

$divEle.fadeIn(5000);

5秒后透明度渐变为0.4

$divEle.fadeTo(5000,0.4);

补充

each方法的使用:简易版本的for循环

<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
</body>

$('div').each(function(index){console.log(index)})

$('div').each(function(index,obj){console.log(index,obj)}) //第一个参数索引,第二个参数为数组里的标签对象

第二种使用方式
// each里面第一个参数放容器对象,第二个参数放函数
$.each(['egon','jason','tank'],function(index,obj){console.log(index,obj)})
VM400:1 0 "egon"   
VM400:1 1 "jason"
VM400:1 2 "tank"

data方法:能够让标签帮我们存储数据,用户肉眼看不见

$('div').data('message','放心去吧,你老婆我会好好照顾的!')
S.fn.init(10) [div, div, div, div, div, div, div, div, div, div, prevObject: S.fn.init(1)]
$('div').first().data('message')
"放心去吧,你老婆我会好好照顾的!"
$('div').last().data('message')
"放心去吧,你老婆我会好好照顾的!"

$('div').first().data('xxx')
undefined
$('div').first().removeData('message') //用于临时存储数据,隐性存储,使用完要记得清除
w.fn.init [div#d1, prevObject: w.fn.init(10)]
           
$('div').first().data('message')
undefined
$('div').last().data('message')
"放心去吧,你老婆我会好好照顾的!"
原文地址:https://www.cnblogs.com/surpass123/p/12926602.html