14jQuery操作DOM、事件

来源:互联网 发布:淘宝活动第三方平台 编辑:程序博客网 时间:2024/06/06 03:34

jQuery操作DOM

  • 读写节点

  • 增删节点

    创建DOM节点、插入DOM节点、删除DOM节点

  • 样式操作

  • 遍历节点

读写节点

  • 读写节点的HTML内容

    obj.html() / obj.html( “123” )

  • 读写节点的文本内容

    obj.text() / obj.text( “123” )

  • 读写节点的value属性值

    obj.val() / obj.val( “abc” )

  • 读写节点的属性值

    obj/attr( “属性名” ) / obj.val( “属性名”, “属性值” )

增删节点

  • 创建节点

    $( “节点内容” )

  • 插入DOM节点

    parent.append( obj ) 作为最后一个子节点添加进来

    parent.prepend( obj ) 作为第一个子节点添加进来

    brother.after( obj ) 作为下一个兄弟节点添加进来

    brother.before( obj ) 作为上一个兄弟添加进来

  • 删除DOM节点

    obj.remove() 删除节点

    obj.remove(selector) 只删除满足selector的节点

    obj.empty() 清空节点

  • 样式操作

    addClass(“ ”) 追加样式

    removeClass(“ ”) 移除指定样式

    removeClass() 移除所有样式

    toggleClass(“ ”) 切换样式

    hasClass(“ ”) 判断是否有某个样式

    css(“ ”) 读取css的值

    css(“ ”, “ ”) 设置多个样式

遍历节点

children() / children(selector) 直接子节点

next() / next(selector) 下一个兄弟节点

prev() / prev(selector) 上一个兄弟节点

siblings() / siblings(selector) 所有兄弟

find(selector) 查找满足选择器的所有后代

parent() 父节点

case:

<script scr=”jquery”></script><style>    .big { font-size: 50px; }    .important { color:red; }</style><script>    $(function(){        //1.读写节点        //1.1 html() == innnerHTML        console.log( $(“p:first”).html() );                ---> jQuery支持<b>读写</b>节点        $( “p:first” ).html( “jQuery支持<u>读写</u>节点” );---> jQuery支持<b>读写</b>节点        //1.2 html() == innerText        //1.3 val() == value        console.log( $(“:button:first”).val() );           ---> 如1.3图        $(“:button:first”).val( “bbb” );                           //1.4 attr() == setAttribute()+getAttribute()        console.log( $(“img:first”).attr (“src”));         ---> 如1.4图        $(“img:first”).attr(“src”, ”2.jpg”);        //3.查询某节点的亲戚        //假设别人传给我如下节点        var gz = $(“#gz”);        //假设处理了该节点,又要处理它的亲戚        console.log(gz.parent());        console.log(gz.prev());        console.log(gz.siblings());        //查询后代        var ul = $(“ul”);        console.log(ul.find(“li:not(li[id])”)); //不带id的li        //4.样式操作        $(“p:first”).addClass(“big”).addClass(“important”);        //变大、变红        $(“p:first”).removeClass(“big”);                       //移除放大        console.log($(“p:first”).hasClass(“big”));             ---> false    });    //2.增删节点    如2图    //2.1增加节点    function f1() {        var li = $(“<li>Hangzhou</li>”);        $(“ul”).prepend(li);    }    //2.2插入节点    function f2() {        var li = $(“<li>Nanjing</li>”);        $(“#gz”).after(li);    }    //2.3删除节点    function f3() {        $(“li:last”).remove();    }    //4切换样式     如4.图    //判断有没有样式,有则删除,没有则增加    function chg() {        $(“p:first”).toggleClass(“important”);    }</script><body>    <p>jQuery支持<b>读写</b>节点</P>    <p>jQuery支持<b>增删</b>节点</P>    <p><input type=”button” value=”aaa” /></P>    <p><img src=”1.jpg”></P>    <p>        <input type=”button” value=”add” onclick=”f1();” />        <input type=”button” value=”insert” onclick=”f2();” />        <input type=”button” value=”delete” onclick=”f3();” />    </P>    <ul>        <li>Beijing</li>        <li>Shanghai</li>        <li id=”gz”>Guangzhou</li>        <li>Shenzhen</li>        <li>Tianjin</li>    </ul>    <p>        <input type=”button” value=”change” onclick=”chg();” />    </P></body>

1.3图

1.4图

2.图增删节点

4.图jQuery操作节点

jQuery开发中的对象

  • $()获得的对象就是jQuery对象

    • 选择器$(“p”)

    • 将DOM转换为jQuery对象:$(btn)

    • 创建新节点:$(“

    • 杭州

注意:

  • 只有jQuery对象才能调jQuery方法

  • 只有DOM对象才能调DOM方法

  • DOM对象转换为jQuery对象

    $(DOM对象)

  • jQuery对象转换为DOM对象:

    obj[i]

    目的:调用对方的方法

jQuery事件处理

事件处理

  • 使用jQuery实现时间绑定

  • 获得事件对象event

  • 事件对象的常用属性

事件冒泡

  • 什么是事件冒泡

  • 如何取消事件冒泡

合成事件

  • jQuery合成事件种类

模拟操作

  • 模拟操作的语法

使用jQuery实现事件绑定

  • 语法:

    $obj.bind(事件类型,事件处理函数)

    如:$obj.bind( ‘click’, fn );

    简写形式:$obj.click(fn);

    注:$obj.click()则代表触发了click事件

  • 获得事件对象event

    只需要为事件处理函数传递任意一个参数

    如:$obj.click( function(e){…} )

    e就是事件对象,但已经经过jQuery对底层事件对象的封装

    封装后的事件对象可以方便地兼容各浏览器

  • 事件对象的常用属性

    获取事件源 e.target, 返回值是DOM对象

    获取鼠标点击的坐标

    e.pageXe.pageY

事件冒泡

  • 什么是事件冒泡

    子节点产生的事件会以依次向上抛给父节点

  • 如何取消事件冒泡

    e.stopPropagation() 可以取消事件冒泡

    $(‘a’).click( (function(e) {    alert(‘click a url’);    e.stopPropagation();});

jQuery的合成事件种类

hover(mouseenter, mouseleave) 模拟光标悬停事件toggle() 在多个事件响应中切换

case:

功能实现:增加一张图片,鼠标悬停放大,移除变回原始大小

<style>    .big { width:360px; height:360px; }</style><script src=”jquery-1.11.1.js”></script><script>    //window.onload在网页只能写一次,否则会被后者覆盖    //$(function(){ } )在网页上可以写一次    $(function() {        //给button绑定单击事件        $(“:button:first”).click(function(e){            albert(“hello”);        });        //给图片绑定hover事件        $(“img”).hover(            function(){                $(this).addClass(“big”);                //$(this).css();                //$(this).width().height();                //$(this).attr(“style”, “”);                //$(this).attr(“class”, “”);            },            function() {                $(this).removeClass(“big”);            }        );        //给button2绑定单击事件        $(“:button:eq(1)”).click(function(){            //让图片在显示与隐藏之间切换            $(“img”).toggle();        });    });</script><body>    <p>        <input type=”button” value=”button1”>        <input type=”button” value=”button2”>    </p>    <img src=”1.jpg”></body>

模拟操作的语法

$obj.trigger(事件类型)

如:$obj.trigger( “focus” );

简写形式 $obj.focus();

case:auto mark

功能事项:增加一组姓名和文本框,点击自动打分按钮,逐个切入文本框,并随机打分

<script src=”jquery-1.11.1.js”></script><script>    function auto_mark() {        var texts = $(“:text”);        var i = 0;        var timer = setInterval(function(){            if(i==text.length){                clearInterval(timer);            }            var score = Math.round( Math.random()*100 );            texts.eq(i++).trigger(“focus”).val(score);        }, 1000 );    }</script><body>    <p><input type=”button” value=”mark” onclick=”auto_mark”>    <p>Zhangsan<input type=”text”></p>    <p>Lisi<input type=”text”></p>    <p>Wangwu<input type=”text”></p>    <p>Zhaoliu<input type=”text”></p></body>

这里写图片描述

jQuery动画

  • 显示、隐藏的动画效果

    • show() / hide()

    • 作用:通过改变元素的宽度和高度来实现显示或隐藏

    • 用法:$obj.show(执行时间,回调函数);

      执行时间:slow、normal、fast或毫秒数

      回调函数:动画执行完毕之后要执行的函数

  • 上下滑动式动画效果

    • slideDown() / slideUp()

    • 作用:通过改变高度来实现显示或者隐藏的动画效果

    • 用法:同show() / hide()

  • 淡入淡出式动画效果

    • fadeIn() / fadeOut()

    • 作用:通过改变不透明度opacity来实现显示或者隐藏

    • 用法:同show() / hide()

  • 自定义动画效果

    • animate(偏移位置,执行时间,回调函数)

    • 偏移位置:{ }描述动画执行之后元素的样式

    • 执行时间:毫秒数

    • 回调函数:动画执行结束后要执行的函数

      $(“div”).click( function(){

      $(this).animate( {‘left’: ‘500px’}, 4000 );$(this).animate({‘top’: ‘300px’}, 2000);

      });

case:advertisement

功能实现:点击按钮,广告收起,或者3s后自动收起

<style>    #advertisement { border/height }    #advertisement input { float:right; margin:10px auto; }</style><script src=”jquery-1.11.1.js”></script><script>    $(function(){        //给按钮X绑定单击事件        $(“#advertisement :button”).click(function(){      //派生选择器 #id :element            //让广告由下向上收起直到消失            $(“advertisement”).slideUp(1000);          //收起时间        });        //页面加载后,延迟3s自动点击X按钮收起广告        setTimeout(function(){            $(“#advertisement :button”).trigger(“click”);        }, 3000);    });</script><body>    <div id=”advertisement”>        <input type=”button” value=”X”>    </div></body>

case

功能实现:增加一张图片,使用不同的方式实现该图片显示/隐藏的动画效果

自定义动画,使得该图片向右移动后再向下移动,隐藏

鼠标悬停:向右运动,然后回到原位

<style>    #msg { display:none; border/width/padding... }    img{ position:relative; }                           //动画基于定位</style><script src=”jquery-1.11.1.js”></script><script>    function show() { $( “img”).show() }    //第二个参数是函数,动画结束时被调用,称为回调函数    //回调函数:逻辑完成后自动调用的函数    function hide() { $(“img”).hide(3000, function(){        alert(“end cartoon”);    //动画底层的实现原理:    //通过定时器不断的修改元素的样式就是动画    //定时器相当于线程,所以动画方法相当于启动论文支线程,    //主线程启动支线程后不等待,立刻执行下一行代码,而支线程3s后执行完成        console.log(“over”);    }); }    function prompt() { $(div).fadeIn(2000).fadeOut(1000) }    function custom() {         $(“img”).animate({‘left’:’500px’}, 2000).animate({‘top’:’300px’}, 2000).fadeOut(2000);         }    $(function(){        $(“img”).hover(            function() { $(this).animate( {‘left’:’1200px’}, 500 ); },            function() { $(this).animate( {‘left’:’0’}, 500 ); }        );    });</script><body>    <p>        <input type=”button” value=”show” onclick=”show();”>        <input type=”button” value=”hide” onclick=”hide();”>        <input type=”button” value=”prompt” onclick=”prompt();”>        <input type=”button” value=”custom” onclick=”custom();”>    </p>    <p><img src=”1.jpg”></p>    <div id=”msg”>Successful operation</div></body>

事件定义:

  • 直接绑定
    和js一样
  • 后绑定
    • 页面加载后:$(function(){})
    • 后绑定事件:$(“:button”).click(function(){})
  • 取消事件
    return false

事件对象:

  • 什么是事件对象

    和js一样

  • 如何获取事件对象

    • 直接绑定事件时
      • 和js一样
    • 后绑定事件时
      • 和js一样
      • 取得的event对象时经过jQuery封装后的对象

事件冒泡

  • 什么是事件冒泡机制

    和js一样

    取消冒泡:e.stopPaopagation()

  • 作用:

    和js一样

  • 获取事件源

e.target