02 jQuery 选择器以及事件

jQuery 选择器以及事件

1. 操作标签

1.1

# 1. 操作类
"""
js版本						Query版本
classList.add()					addClass()
classList.remove()				removeClass()
classList.contains()				hasClass()      # 判断一个类是否存在
classList.toggle(class, true|false)		toggleClass()   #第一个参数为要在元素中移除的类名,并返回 false。
如果该类名不存在则会在元素中添加类名,并返回 true。
"""


# 2. css操作   Ele.css('属性','赋值')
<p>111</p>
<p>222</p>
"""一行代码将第一个p标签变成红色第二个p标签变成绿色"""
$('p').first().css('color','red').next().css('color','green')
# jQuery的链式操作 使用jQuery可以做到一行代码操作很多标签
# jQuery对象调用jQuery方法之后返回的还是当前jQuery对象 也就可以继续调用其他方法


# 3. 位置操作
offset()    # 相对于浏览器窗口
  $('p').offset()
position()  # 相对于父标签
  $('p').position()
scrollLeft()
scrollTop()		  # 掌握
  $(window).scrollTop()   # 括号内不加参数就是获取(获取当前窗口位置(滚动条到哪了))
  $(window).scrollTop(0)  # 加了参数就是设置(让他滚到哪)
  $(window).scrollTop(500)

	
# 4. 尺寸
$('p').height()  # 文本
$('p').width()
$('p').innerHeight()  # 文本+padding
$('p').innerWidth()
$('p').outerHeight()  # 文本+padding+border
$('p').outerWidth()

1.2

# 1. 标签文本操作
操作标签内部文本
js			jQuery
innerText		text()  括号内不加参数就是获取加了就是设置
innerHTML		html()

$('div').text()   # 获取div内部文本
$('div').html()   # 获取div的html(有标签)

$('div').text('你们都是我的大宝贝')           # 有效果
$('div').html('你个臭妹妹')                   # 有效果
$('div').text('<h1>你们都是我的大宝贝</h1>')   # 没有h1标签效果
$('div').html('<h1>你个臭妹妹</h1>')           # 有效果


# 2. 获取值操作
js			jQuery
.value			.val()

$('#d1').val()    # 假如d1是一个文本框,就是获取文本框用户输入的值
$('#d1').val('520快乐')  # 括号内不加参数就是获取加了就是设置


# 3. 获取文件
$('#d2').val()
"C:\fakepath\01_测试路由.png"
$('#d2')[0].files[0]  # 牢记两个对象之间的转换
File {name: "01_测试路由.png", lastModified: 1557043083000, lastModifiedDate: Sun May 05 2019 15:58:03 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 28733, …}


# 4. 属性操作
"""
js中			jQuery
setAttribute()		attr(name,value)
getAttribute()		attr(name)
removeAttribute()	removeAttr(name)

在用变量存储对象的时候 js中推荐使用	
	XXXEle			标签对象
jQuery中推荐使用
	$XXXEle			jQuery对象
"""

# 获取标签
let $pEle = $('p')
# 获取属性值
$pEle.attr('id')
$pEle.attr('class')
# 修改属性值
$pEle.attr('class','c1')
$pEle.attr('id','id666')
# 移除属性值
$pEle.removeAttr('password')

"""
对于标签上有的能够看到的属性和自定义属性用attr
对于返回布尔值比如checkbox radio option是否被选中用prop
"""
$('#d2').prop('checked')
false
$('#d2').prop('checked')
true
$('#d3').prop('checked',true)
$('#d3').prop('checked',false)


# 5. 文档处理
"""
js				jQuery
createElement('p')		$('<p>')
appendChild()			append()
"""
let $pEle = $('<p>')
$pEle.text('你好啊 草莓要不要来几个?')
$pEle.attr('id','d1')
$('#d1').append($pEle) === $pEle.appendTo($('#d1'))  # 内部尾部追加

$('#d1').prepend($pEle)  # 内部头部追加
$pEle.prependTo($('#d1'))

$('#d2').after($pEle)  # 放在某个标签后面
$pEle.insertAfter($('#d1'))

$('#d1').before($pEle)
$pEle.insertBefore($('#d2'))

$('#d1').remove()  # 将标签从DOM树中删除

$('#d1').empty()  # 清空标签内部所有的内容

2. 事件

2.1 事件绑定的两种方式

// 第一种
    $('#d1').click(function () {
            alert('别说话 吻我')
    });

// 第二种(功能更加强大 还支持事件委托)
    $('#d2').on('click',function () {
            alert('借我钱买草莓 后面还你')
    })

2.2 克隆事件

<button id="d1">点击克隆</button>

<script>
    $('#d1').on('click',function () {
        // console.log(this)  // this指代是当前被操作的标签对象
        // $(this).clone().insertAfter($('body'))  // clone默认情况下只克隆html和css 不克隆事件
        $(this).clone(true).insertAfter($('body'))  // 括号内加true即可克隆事件

    })
</script>

2.3 自定义模态框

show code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>自定义模态框</title>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <style>
    .cover {
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background-color: darkgrey;
      z-index: 999;
    }
    .modal {
      width: 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>
  $("#i0").click(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>

2.4 左侧菜单栏

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style>
        .left {
            float: left;
            background-color: darkgray;
            width: 20%;
            height: 100%;
            position: fixed;
        }
        .title {
            font-size: 36px;
            color: white;
            text-align: center;
        }
        .items {
            border: 1px solid black;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="left">
    <div class="menu">
        <div class="title">菜单一
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
        <div class="title">菜单二
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
        <div class="title">菜单三
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
    </div>
</div>

<script>
    $('.title').click(function () {
        // 先给所有的items加hide
        $('.items').addClass('hide')
        // 然后将被点击标签内部的hide移除
        $(this).children().removeClass('hide')
    })
</script>
</body>
</html>

2.5 返回顶部

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style>
        .hide {
            display: none;
        }
        #d1 {
            position: fixed;
            background-color: black;

            right: 20px;
            bottom: 20px;
            height: 50px;
            width: 50px;
        }
    </style>
</head>
<body>
<a href="" id="d1"></a>
<div style="height: 500px;background-color: red"></div>
<div style="height: 500px;background-color: greenyellow"></div>
<div style="height: 500px;background-color: blue"></div>
<a href="#d1" class="hide">回到顶部</a>

<script>
    $(window).scroll(function () {
        if($(window).scrollTop() > 300){
            $('#d1').removeClass('hide')
        }else{
            $('#d1').addClass('hide')
        }
    })
</script>
</body>
</html>

2.6 自定义登陆校验

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p>username:
    <input type="text" id="username">
    <span style="color: red"></span>
</p>
<p>password:
    <input type="text" id="password">
    <span style="color: red"></span>
</p>
<button id="d1">提交</button>

<script>
    let $userName = $('#username')
    let $passWord = $('#password')
    $('#d1').click(function () {
        // 获取用户输入的用户名和密码 做校验
        let userName = $userName.val()
        let passWord = $passWord.val()
        if (!userName){
            $userName.next().text("用户名不能为空")
        }
        if (!passWord){
            $passWord.next().text('密码不能为空')
        }
    })
    $('input').focus(function () {
        $(this).next().text('')
    })
</script>
</body>
</html>

2.7 input实时监控

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>k</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="d1">

<script>
    $('#d1').on('input',function () {
        console.log(this.value)
    })
</script>
</body>
</html>

2.8 hover事件

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p id="d1">到家啊就是度假酒店</p>

<script>
    // $("#d1").hover(function () {  // 鼠标悬浮 + 鼠标移开
    //     alert(123)
    // })

    $('#d1').hover(
        function () {
            alert('我来了')  // 悬浮
    },
        function () {
            alert('我溜了')  // 移开
        }
    )
</script>
</body>
</html>

2.9 键盘按键按下事件

show code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

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

3. jQuery事件补充

posted @ 2021-09-06 16:03  超暖  阅读(96)  评论(0)    收藏  举报