Web前端学习笔记—— jQuery之操作节点、属性、尺寸和位置

jQuery节点操作

创建节点

// $(htmlStr)
// htmlStr:html格式的字符串
$('<span-这是一个span元素</span-');

添加节点

append  appendTo	在被选元素的结尾插入内容
prepend prependTo	在被选元素的开头插入内容
before				在被选元素之后插入内容
after				在被选元素之前插入内容

清空节点与删除节点

  • empty:清空指定节点的所有元素,自身保留(清理门户)
$('div').empty(); // 清空div的所有内容(推荐使用,会清除子元素上绑定的内容,源码)
$('div').html('');// 使用html方法来清空元素,不推荐使用,会造成内存泄漏,绑定的事件不会被清除。
  • remove:相比于empty,自身也删除(自杀)
$('div').remove();

克隆节点

  • 作用:复制匹配的元素
// 复制$(selector)所匹配到的元素(深度复制)
// cloneNode(true)
// 返回值为复制的新元素,和原来的元素没有任何关系了。即修改新元素,不会影响到原来的元素。
$(selector).clone();

案例

  • 城市选择 [11-城市选择案例.html]
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        select {
            width: 200px;
            background-color: teal;
            height: 200px;
            font-size: 20px;
        }

        .btn-box {
            width: 30px;
            display: inline-block;
            vertical-align: top;
        }
    </style>
    <script src="vendor/jquery.js"></script>
    <script>
        $(function () {

            //全部向右功能
            $("#btn-sel-all").click(function () {
                // 1. 获取左边所有的option
                var options = $("#src-city>option");
                // 2. 添加到右边
                $("#tar-city").append(options);
            });

            //全部向左
            $("#btn-sel-none").click(function () {
                var options = $("#tar-city>option");
                $("#src-city").append(options);
            });

            //让左边选中的元素移动到右边
            $("#btn-sel").click(function () {
                // 1. 获取到左边选中的option
                // :selected 过滤选择器,获取到选中的部分
                var options = $("#src-city>option:selected");
                // 2. 添加到右边
                $("#tar-city").append(options);
            });

            $("#btn-back").click(function () {
                var options = $("#tar-city>option:selected");
                $("#src-city").append(options);
            });
        });
    </script>
</head>

<body>
<h1>城市选择:</h1>
<select id="src-city" name="src-city" multiple>
    <option value="1">北京</option>
    <option value="2">上海</option>
    <option value="3">深圳</option>
    <option value="4">广州</option>
    <option value="5">西红柿</option>
</select>
<div class="btn-box">
    <!--实体字符-->
    <button id="btn-sel-all"> &gt;&gt; </button>
    <button id="btn-sel-none"> &lt;&lt; </button>
    <button id="btn-sel"> &gt;</button>
    <button id="btn-back"> &lt; </button>
</div>
<select id="tar-city" name="tar-city" multiple>
</select>
</body>

</html>

  • 删除表格 [12 表格删除案例.html]
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .wrap {
            width: 410px;
            margin: 100px auto 0;
        }

        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
        }

        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "΢ÈíÑźÚ";
            color: #fff;
        }

        td {
            font: 14px "΢ÈíÑźÚ";
        }

        td a.get {
            text-decoration: none;
        }

        a.del:hover {
            text-decoration: underline;
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }

        .btnAdd {
            width: 110px;
            height: 30px;
            font-size: 20px;
            font-weight: bold;
        }

        .form-item {
            height: 100%;
            position: relative;
            padding-left: 100px;
            padding-right: 20px;
            margin-bottom: 34px;
            line-height: 36px;
        }

        .form-item > .lb {
            position: absolute;
            left: 0;
            top: 0;
            display: block;
            width: 100px;
            text-align: right;
        }

        .form-item > .txt {
            width: 300px;
            height: 32px;
        }

        .mask {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100%;
            background: #000;
            opacity: 0.15;
            display: none;
        }

        .form-add {
            position: fixed;
            top: 30%;
            left: 50%;
            margin-left: -197px;
            padding-bottom: 20px;
            background: #fff;
            display: none;
        }

        .form-add-title {
            background-color: #f7f7f7;
            border-width: 1px 1px 0 1px;
            border-bottom: 0;
            margin-bottom: 15px;
            position: relative;
        }

        .form-add-title span {
            width: auto;
            height: 18px;
            font-size: 16px;
            font-family: ËÎÌå;
            font-weight: bold;
            color: rgb(102, 102, 102);
            text-indent: 12px;
            padding: 8px 0px 10px;
            margin-right: 10px;
            display: block;
            overflow: hidden;
            text-align: left;
        }

        .form-add-title div {
            width: 16px;
            height: 20px;
            position: absolute;
            right: 10px;
            top: 6px;
            font-size: 30px;
            line-height: 16px;
            cursor: pointer;
        }

        .form-submit {
            text-align: center;
        }

        .form-submit input {
            width: 170px;
            height: 32px;
        }
    </style>
    <script src="vendor/jquery.js"></script>
    <script>
        $(function () {
            // 1. 给delete绑定点击事件
            $(".get").click(function () {
                // 2. 删除该按钮对应的行
                $(this).parent().parent().remove();
            });
			$("#btn").click(function() {
				$("#j_tb").empty();
			});

        });
    </script>

</head>

<body>
<div class="wrap">
	<input type="button" value="清空内容" id="btn">
    <table>
        <thead>
        <tr>
            <th>课程名称</th>
            <th>所属学院</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="j_tb">
        <tr>
            <!-- <td><input type="checkbox"/></td> -->
            <td>JavaScript</td>
            <td>传智播客-前端与移动开发学院</td>
            <td><a href="javascrip:;" class="get">DELETE</a></td>
        </tr>
        <tr>
            <!-- <td><input type="checkbox"/></td> -->
            <td>css</td>
            <td>传智播客-前端与移动开发学院</td>
            <td><a href="javascrip:;" class="get">DELETE</a></td>
        </tr>
        <tr>
            <!-- <td><input type="checkbox"/></td> -->
            <td>html</td>
            <td>传智播客-前端与移动开发学院</td>
            <td><a href="javascrip:;" class="get">DELETE</a></td>
        </tr>
        <tr>
            <!-- <td><input type="checkbox"/></td> -->
            <td>jQuery</td>
            <td>传智播客-前端与移动开发学院</td>
            <td><a href="javascrip:;" class="get">DELETE</a></td>
        </tr>
        </tbody>
    </table>
</div>
</body>

</html>

  • 根据数据生成表格 [13-表格生成案例.html]


<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
        }

        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }

        td {
            font: 14px "微软雅黑";
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>
    <script src="vendor/jquery.js"></script>
    <script>
        // 模拟从后台拿到的数据
        var data = [{
            name: "传智播客",
            url: "http://www.itcast.cn",
            type: "IT最强培训机构"
        }, {
            name: "黑马程序员",
            url: "http://www.itheima.com",
            type: "大学生IT培训机构"
        }, {
            name: "传智前端学院",
            url: "http://web.itcast.cn",
            type: "前端的黄埔军校"
        }];

        
        $(function () {
            $("#j_btnGetData").click(function () {

                var htmlStr = "";
                for(var i = 0; i< data.length;i++){
                    //data[i].name   传智播客
                    //data[0].url = "http://www.itcast.cn"
                    htmlStr += "<tr><td>"+data[i].name+"</td><td>"+data[i].url+"</td><td>"+data[i].type+"</td></tr>";
                }


                $("#j_tbData").html(htmlStr);
            });
        });
    </script>
</head>

<body>
<input type="button" value="获取数据" id="j_btnGetData" />
<table>
    <thead>
    <tr>
        <th>标题</th>
        <th>地址</th>
        <th>说明</th>
    </tr>
    </thead>
    <tbody id="j_tbData">

    </tbody>
</table>
</body>

</html>

  • 添加和删除表格数据 [14-动态数据添加和删除.html]
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .wrap {
            width: 410px;
            margin: 100px auto 0;
        }

        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
        }

        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }

        td {
            font: 14px "微软雅黑";
        }

        td a.get {
            text-decoration: none;
        }

        a.del:hover {
            text-decoration: underline;
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }

        .btnAdd {
            width: 110px;
            height: 30px;
            font-size: 20px;
            font-weight: bold;
        }

        .form-item {
            height: 100%;
            position: relative;
            padding-left: 100px;
            padding-right: 20px;
            margin-bottom: 34px;
            line-height: 36px;
        }

        .form-item > .lb {
            position: absolute;
            left: 0;
            top: 0;
            display: block;
            width: 100px;
            text-align: right;
        }

        .form-item > .txt {
            width: 300px;
            height: 32px;
        }

        .mask {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100%;
            background: #000;
            opacity: 0.6;
            display: none;
        }

        #j_hideFormAdd {
            width: 22px;
            height: 22px;
            cursor: pointer;
            text-align: center;
            line-height: 22px;
            font-size: 18px;
        }
        #j_hideFormAdd:hover {
            background-color: skyblue;
        }
        .form-add {
            position: fixed;
            top: 30%;
            left: 50%;
            margin-left: -197px;
            padding-bottom: 20px;
            background: #fff;
            display: none;
        }

        .form-add-title {
            background-color: #f7f7f7;
            border-width: 1px 1px 0 1px;
            border-bottom: 0;
            margin-bottom: 15px;
            position: relative;
        }

        .form-add-title span {
            width: auto;
            height: 18px;
            font-size: 16px;
            font-family: 宋体;
            font-weight: bold;
            color: rgb(102, 102, 102);
            text-indent: 12px;
            padding: 8px 0px 10px;
            margin-right: 10px;
            display: block;
            overflow: hidden;
            text-align: left;
        }

        .form-add-title div {
            width: 16px;
            height: 20px;
            position: absolute;
            right: 10px;
            top: 6px;
            font-size: 30px;
            line-height: 16px;
            cursor: pointer;
        }

        .form-submit {
            text-align: center;
        }

        .form-submit input {
            width: 170px;
            height: 32px;
        }
    </style>
    <script src="vendor/jquery.js"></script>
    <script>
        $(function () {
            //需求1:点击添加按钮,显示遮罩层和表单添加内容区;
            //需求2:点击X按钮,隐藏遮罩层和表单添加内容区;
            //需求3:点击表单添加内容区里面的添加按钮,组合一个tr添加到tbody中;
            //需求4:点击get所在的a链接删除


            //需求1:点击添加按钮,显示遮罩层和表单添加内容区;
            $("#j_btnAddData").click(showOrHide);
            //需求2:点击X按钮,隐藏遮罩层和表单添加内容区;
            $("#j_hideFormAdd").click(showOrHide);
            //需求3:点击表单添加内容区里面的添加按钮,组合一个tr添加到tbody中;
            $("#j_btnAdd").click(function () {
                //获取课程名称和院校的内容(input的value属性值);
                var val1 = $("#j_txtLesson").val();//获取value属性用val();
                var val2 = $("#j_txtBelSch").val();//获取value属性用val();

                //bug3: val1和val2内容不能为空;
                if(val1.trim() === "" || val2.trim() === ""){
                    alert("对不起,输入的内容不能为空!");
                    $("#j_txtLesson").val("");
                    $("#j_txtBelSch").val("传智播客-前端与移动开发学院");
                    return;
                }

                //生成tr添加到tbody中;
                var jqTr = $("<tr></tr>");
                //为tr里面设置td而且赋值上内容;
                jqTr.html('<td>'+val1+'</td><td>'+val2+'</td><td><a href="javascrip:void(0);" class="get">GET</a></td>');
                //在把tr添加到tbody中;
                $("#j_tb").append(jqTr);

                //bug1: 隐藏遮罩层和表单添加内容区;
                showOrHide();
                //bug2: 添加完毕数据以后,清空和重新设置vlaue值;
                $("#j_txtLesson").val("");
                $("#j_txtBelSch").val("传智播客-前端与移动开发学院");

                //bug4:新创建的tr里面的a链接绑定事件;
                jqTr.find("a").click(function () {
                    $(this).parent("td").parent("tr").remove();
                });
            });

            //需求4:点击get所在的a链接删除(新创建的a链接没有该事件)
            $("#j_tb a").click(function () {
                $(this).parent("td").parent("tr").remove();
            });


            //显示或者隐藏盒子
            function showOrHide() {
                //显示遮罩层和表单添加内容区;
                $("#j_mask").toggle();
                $("#j_formAdd").toggle();
            }
        });
    </script>

</head>

<body>

    <!--按钮和表单-->
    <div class="wrap">
        <div>
            <input type="button" value="添加数据" id="j_btnAddData" class="btnAdd"/>
        </div>
        <table>
            <thead>
            <tr>
                <th>课程名称</th>
                <th>所属学院</th>
                <th>已学会</th>
            </tr>
            </thead>
            <tbody id="j_tb">
            <tr>
                <td>JavaScript</td>
                <td>传智播客-前端与移动开发学院</td>
                <td><a href="javascrip:;" class="get">delete</a></td>
            </tr>
            <tr>
                <td>css</td>
                <td>传智播客-前端与移动开发学院</td>
                <td><a href="javascrip:;" class="get">delete</a></td>
            </tr>
            <tr>
                <td>html</td>
                <td>传智播客-前端与移动开发学院</td>
                <td><a href="javascrip:;" class="get">delete</a></td>
            </tr>
            <tr>
                <td>jQuery</td>
                <td>传智播客-前端与移动开发学院</td>
                <td><a href="javascrip:;" class="get">delete</a></td>
            </tr>
            </tbody>
        </table>
    </div>
    <!--遮罩层-->
    <div id="j_mask" class="mask"></div>
    <!--添加数据的表单-->
    <div id="j_formAdd" class="form-add">
        <div class="form-add-title">
            <span>添加数据</span>

            <div id="j_hideFormAdd">×</div>
        </div>
        <div class="form-item">
            <label class="lb" for="j_txtLesson">课程名称:</label>
            <input class="txt" type="text" id="j_txtLesson" placeholder="请输入课程名称">
        </div>
        <div class="form-item">
            <label class="lb" for="j_txtBelSch">所属学院:</label>
            <input class="txt" type="text" id="j_txtBelSch" value="传智播客-前端与移动开发学院">
        </div>
        <div class="form-submit">
            <input type="button" value="添加" id="j_btnAdd">
        </div>
    </div>

</body>


</html>

jQuery操作属性

attr操作

  • 设置单个属性
// 第一个参数:需要设置的属性名
// 第二个参数:对应的属性值
$obj.attr(name, value);
// 用法举例
$('img').attr('title','哎哟,不错哦');
$('img').attr('alt','哎哟,不错哦');
  • 设置多个属性
// 参数是一个对象,包含了需要设置的属性名和属性值
$obj.attr(obj)
// 用法举例
$('img').attr({
    title:'哎哟,不错哦',
    alt:'哎哟,不错哦',
    style:'opacity:.5'
});
  • 获取属性
// 传需要获取的属性名称,返回对应的属性值
$obj.attr(name)
// 用法举例
var oTitle = $('img').attr('title');
alert(oTitle);
  • 移除属性
// 参数:需要移除的属性名,
$obj.removeAttr(name);
// 用法举例
$('img').removeAttr('title');

prop操作

  • 在jQuery1.6之后,对于checked、selected、disabled这类boolean类型的属性来说,不能用attr方法,只能用prop方法。
// 设置属性
$(':checked').prop('checked',true);
// 获取属性
$(':checked').prop('checked');// 返回true或者false

val()/text/()html()

$obj.val()		获取或者设置表单元素的value属性的值
$obj.html() 	对应innerHTML
$obj.text()		对应innerText/textContent,处理了浏览器的兼容性

案例

  • 表格全选反选 [15-表格全选反选.html]
<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .wrap {
      width: 300px;
      margin: 100px auto 0;
    }

    table {
      border-collapse: collapse;
      border-spacing: 0;
      border: 1px solid #c0c0c0;
    }

    th,
    td {
      border: 1px solid #d0d0d0;
      color: #404060;
      padding: 10px;
    }

    th {
      background-color: #09c;
      font: bold 16px "微软雅黑";
      color: #fff;
    }

    td {
      font: 14px "微软雅黑";
    }

    tbody tr {
      background-color: #f0f0f0;
    }

    tbody tr:hover {
      cursor: pointer;
      background-color: #fafafa;
    }
  </style>
  <script src="jquery-1.12.1.js"></script>
  <script>
    $(function () {

      //全选和全不选
      //获取thead中的复选框,获取他的这个选中的状态

//      $("#j_cbAll").click(function () {
//        //获取当前的复选框的选中状态
//        var flag= $(this).prop("checked");
//        //判断选中状态
//        if(flag){
//          $("#j_tb").find("input").prop("checked",true);
//        }else{
//          $("#j_tb").find("input").prop("checked",false);
//        }
//      });


      //thead标签中的复选框----全选和全不选
      $("#j_cbAll").click(function () {
        //直接设置tbody中复选框的选中状态和当前点击的复选框的选中状态一致
        $("#j_tb").find("input").prop("checked",$(this).prop("checked"));
      });


      //每个复选框都要注册点击事件
      $("#j_tb").find("input").click(function () {
        //先获取所有的复选框的个数
        var ckLength=$("#j_tb").find("input").length;
        //获取所有选中的复选框的个数
        var checkedLenth=$("#j_tb :checked").length;
        //console.log(ckLength+"====="+checkedLenth);//测试代码
//        if(ckLength==checkedLenth){
//          $("#j_cbAll").prop("checked",true);
//        }else{
//          $("#j_cbAll").prop("checked",false);
//        }
        $("#j_cbAll").prop("checked",checkedLenth==ckLength);
      });


    });
  </script>

</head>

<body>
<div class="wrap">
  <table>
    <thead>
    <tr>
      <th>
        <input type="checkbox" id="j_cbAll"/>
      </th>
      <th>课程名称</th>
      <th>所属学院</th>
    </tr>
    </thead>
    <tbody id="j_tb">
    <tr>
      <td>
        <input type="checkbox"/>
      </td>
      <td>JavaScript</td>
      <td>前端与移动开发学院</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox"/>
      </td>
      <td>css</td>
      <td>前端与移动开发学院</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox"/>
      </td>
      <td>html</td>
      <td>前端与移动开发学院</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox"/>
      </td>
      <td>jQuery</td>
      <td>前端与移动开发学院</td>
    </tr>

    </tbody>
  </table>
</div>
</body>

</html>

  • 打字效果 [16-打字效果.html]
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        @keyframes blink {
            0%,
            100% {
                opacity: 1
            }
            50% {
                opacity: 0
            }
        }

        @-webkit-keyframes blink {
            0%,
            100% {
                opacity: 1
            }
            50% {
                opacity: 0
            }
        }

        @-moz-keyframes blink {
            0%,
            100% {
                opacity: 1
            }
            50% {
                opacity: 0
            }
        }

        .wrap {
            width: 1000px;
            text-align: center;
            margin: 100px auto 0;
        }

        .wrap h1 {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            font-weight: 300;
        }

        .word {
            font-weight: 700;
        }

        .typed-cursor {
            opacity: 1;
            -webkit-animation: blink .7s infinite;
            -moz-animation: blink .7s infinite;
            animation: blink .7s infinite;
            display: none;
        }

        .saySection {
            margin-top: 50px;
        }

        .saySection input {
            font-size: 30px;
        }

        .saySection .txtSay {
            padding-left: 10px;
        }

        .saySection .btnSay {
            display: inline-block;
            padding: 0 20px;
            cursor: pointer;
        }
    </style>
    <script src="vendor/jquery.js"></script>
    <script>
        $(document).ready(function () {
            //需求:封装一个方法,传递进去一个字符串,利用定时器每隔一段时间输出一个内容;完成后清除定时器;
                    //1.页面加载的时候,调用一次,内容为:"红鲤鱼与绿鲤鱼与驴";
                    //2.在input里面输入内容后点击按钮后,在次调用,内容为:input的value值;
            //页面中只能有一个定时器;
            var timer = null;

            //页面加载默认的内容;
            fn("红鲤鱼与绿鲤鱼与驴");
            //点击按钮,显示的是input里面的value值
            $("#btnSay").click(function () {
                fn($("#inValue").val());
            });


            //封装一个方法;
            //步骤:
            //0.显示插入条光标;
            //1.先定义一个变量num;以后可以自增,作为索引值用;然后定义一个定时器;新的字符串;
            //2.定时器里面先把字符串添加到word盒子里面去;然后num++;
            //3.全部输入以后清除定时器;
            //4.隐藏插入条光标;
            function fn(str){
                //0.显示插入条光标;要用定时器,先清除定时器;
                clearInterval(timer);
                $(".typed-cursor").show();
                //1.先定义一个变量num,可以自增;作为索引值用;然后定义一个定时器;新的字符串;
                var num = 0;
                var newStr = "";
                timer = setInterval(function () {
                    //判断:如果能够获取内容就添加,如果不能获取内容了(undefined),那么就清除定时器;
                    if(str[num] !== undefined){
                        //2.定时器里面先把字符串添加到word盒子里面去;然后num++;
                        newStr += str[num];//字符串可以当数组操作;  str.charAt(num);
                        $(".word").text(newStr);
                        num++;
                    }else{
                        //3.全部输入以后清除定时器;
                        clearInterval(timer);
                        //4.隐藏插入条光标;
                        $(".typed-cursor").hide();
                    }
                },300);
            }



        });
    </script>
</head>

<body>

    <div class="wrap">
        <h1>
            You want to say :
            <span class="word"></span>
            <span class="typed-cursor">|</span></h1>
        <div class="saySection">
            <input type="text" id="inValue" class="txtSay"/>
            <input type="button" value="Say" id="btnSay" class="btnSay"/>
        </div>
    </div>

</body>
</html>

jQuery尺寸和位置操作

width方法与height方法

  • 设置或者获取高度,不包括内边距、边框和外边距
// 带参数表示设置高度
$('img').height(200);
// 不带参数获取高度
$('img').height();

获取网页的可视区宽高

// 获取可视区宽度
$(window).width();
// 获取可视区高度
$(window).height();

innerWidth/innerHeight/outerWidth/outerHeight

innerWidth()/innerHeight()	方法返回元素的宽度/高度(包括内边距)。
outerWidth()/outerHeight()  方法返回元素的宽度/高度(包括内边距和边框)。
outerWidth(true)/outerHeight(true)  方法返回元素的宽度/高度(包括内边距、边框和外边距)。

scrollTop与scrollLeft

  • 设置或者获取垂直滚动条的位置
// 获取页面被卷曲的高度
$(window).scrollTop();
// 获取页面被卷曲的宽度
$(window).scrollLeft();

offset方法与position方法

  • offset方法获取元素距离document的位置,position方法获取的是元素距离有定位的父元素(offsetParent)的位置。
// 获取元素距离document的位置,返回值为对象:{left:100, top:100}
$(selector).offset();
// 获取相对于其最近的有定位的父元素的位置。
$(selector).position();

案例:固定导航栏 [17-固定导航栏.html]

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>固定导航栏</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .top, .nav {
            width: 1423px;
            margin: 0 auto;
        }

        .main {
            width: 1000px;
            margin: 0 auto;
        }

        img {
            display: block;
            vertical-align: middle;
        }

    </style>

    <script src="vendor/jquery.js"></script>
    <script>
        //涉及到检测图片的宽高一般我们都用window.onload;
        window.onload = function () {
            //页面滚动以后,被圈去的头部超过第一个盒子的高,给第二个盒子添加固定定位;
            //    (第一个或者第三个盒子改变margin或者padding,为了给第二个盒子占位置)
//            console.log(top);   //不要用top做变量;
//            console.log(location);
//            console.log(history);
//            console.log(navigator);
//            console.log(screen);

            //绑定屏幕/页面滚动事件
            $(window).scroll(function () {
                //console.log($(document).scrollTop());//是方法,不是属性
                //判断:页面被卷去的头部,是否大于第一个盒子的高;
                //alert($(".top").height());
                if($(document).scrollTop() > $(".top").height()){
                    //给第二个盒子添加固定定位;
                    $(".nav").css({"position":"fixed","left":0,"top":0,});
                    //给第一个盒子或者第三个添加padding/margin;
                    $(".main").css("padding-top",$(".nav").height());
                }else{
                    //小于第一个盒子的高的时候,第二个去掉定位,第三个去掉padding;
                    $(".nav").css({"position":"static","left":0,"top":0,});
                    $(".main").css("padding-top",0);
                }
            });


        };
    </script>
</head>

<body>

    <div class="top">
        <img src="images/top.png"/>
    </div>
    <div class="nav">
        <img src="images/nav.png"/>
    </div>
    <div class="main">
        <img src="images/main.png"/>
    </div>


</body>
</html>

案例:电梯导航 [18-电梯导航.html]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>Document</title>
	<style type="text/css">
	*{
		margin:0;padding:0;
	}
	ul{list-style: none;}
	.top,.dian,.jia,.fu,.mei,.bottom{
		width: 1210px;
		margin: 0 auto;
	}
	.subnav
	{
		position: fixed;
		width: 38px;
		height: 200px;
		top:200px;
		left:50%;
		margin-left:605px;
		display: none;
	}
	.subnav li,.back{
		height: 36px;
		border:1px solid #DEDEDE;
		margin-bottom: 5px;
		font-size:0;
		background: url(images/bg.png) no-repeat;
	}
	.subnav li:hover,.subnav li.current,.back
	{
		border:1px solid #ED5759;
		background: #FDEEEE;   /* 只有冲突的时候才会出现层叠 */
		/* 背景颜色 背景图片 背景位置 背景平铺  背景固定 */
		/* css 层叠样式表 */
		font-size:12px;
		color: #ED5759;
		padding-left: 6px;
		padding-top: 2px;
		height: 34px;
		cursor: pointer;
	}
	</style>
	<script type="text/javascript" src="vendor/jquery.js"></script>
	<script type="text/javascript">
	$(document).ready(function() {
		/*alert($(".jia").offset().top);*/
		/*先遍历背景图片*/
		var num=null;  /*声明一个空的变量 计算精灵图的纵坐标*/
		$(".subnav li").each(function(index, el) {
			num=-index*55;  /*我们经过严格的计算,得出纵坐标: 索引号*55*/
			$(el).css("background-position","0px "+num+"px");
		});
		/*滚动屏幕开始*/
		var T=null;
		$(window).scroll(function(event) {
			T=$(document).scrollTop();  /*获取滚动条距离顶部的距离*/
			if(T>=$(".mei").offset().top)
			{
				$(".subnav li").eq(3).addClass('current').siblings().removeClass();
			}
			else if(T>=$(".fu").offset().top)
			{
				$(".subnav li").eq(2).addClass('current').siblings().removeClass();
			}			
			else if(T>=$(".jia").offset().top)
			{
				$(".subnav li").eq(1).addClass('current').siblings().removeClass();
			}
			else if(T>=$(".dian").offset().top)
			{
				$(".subnav li").eq(0).addClass('current').siblings().removeClass();
			}
			else if(T>0)   /*当大于0 就显示*/
			{

				$(".subnav").fadeIn();
			}
			else  /*等于0 就隐藏*/
			{
				$(".subnav").fadeOut();
			}


		});

        /*点击滑动屏幕事件*/
         /* $(".subnav li").eq(0).click(function(event) {
          	    $("html,body").stop().animate({
          	    	"scrollTop":$(".dian").offset().top
          	    },2000);
          	    /*是盒子做动画 这里用body html 
          });
          $(".subnav li").eq(1).click(function(event) {
          	    $("html,body").stop().animate({
          	    	"scrollTop":$(".jia").offset().top
          	    },2000);
          	    /*是盒子做动画 这里用body html 
          });*/

         $(".subnav li").click(function(event) {
             /*alert($(this).index());*/
             $("body,html").stop().animate({
             	 "scrollTop":$(".jd").eq($(this).index()).offset().top
             },2000);
         });
         
        /*返回顶部开始*/

          $(".back").click(function(event) {
          	$("body,html").stop().animate({"scrollTop":0},100)
          });



	});
	</script>
</head>
<body>
	<div class="top">
		<img src="images/top1.png" alt="" />
	</div>
	<div class="jd dian">
	    <img src="images/dian.png" alt="" />
	</div>
	<div class="jd jia">
		<img src="images/jia.png" alt="" />
	</div>
	<div class="jd fu">
		<img src="images/fu.png" alt="" />
	</div>
	<div class="jd mei">
		<img src="images/mei.png" alt="" />
	</div>
	<div class="bottom">
		<img src="images/bottom.png" alt="" />
	</div>
	<div class="subnav">
		<ul>
			<li>电脑数码</li>
			<li>家电通讯</li>
			<li>服饰精品</li>
			<li>美容珠宝</li>
		</ul>
		<div class="back">返回</div>

	</div>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/tichimi3375/article/details/82836834
今日推荐