前端学习:jquery的使用,window对象的补充(三个框,窗口打开与关闭),图片的拖拽,瀑布流,购物车

目录

1.jquery

2.jquery对象和原生对象的互转

3.jQuery对象的增删改查方法

3.window对象的补充

4.图片的拖拽

5.瀑布流

6、购物车


1.jquery

        库   js的脚本库 是对原生dom的封装,是对webAPI的封装 与BOM无关

提供对dom的操作 对属性的操作 对事件的操作 对样式的操作

开源库  兼容好

引入方式:1.本地引入

                   2.CDN(内容分发网络)引入

$   jQuery为定义的全局变量 是一个函数

 console.log($ === jQuery);//true

使用:

        $()      参数:字符串(选择器)或  原生dom对象

提供的方法:

$("div").text("123");//设置文本内容

$("div").css("color","red");//设置样式 p1:属性名称  p2:属性值

 console.log($("div").css("color"));//传一个参数 是获取元素的属性对应的值

jQuery支持链式调用:

        因为jQuery提供的方法返回的依然是jquery对象

         $("div").css("color","red").css("background","blue");

通过jQuery方法找到的元素返回的是一个数组对象,内部会进行隐式迭代,不需要再用for、foreach进行遍历,

        可以通过jQuery对象的eq()方法,通过索引找到对应数组中的元素  返回值依然是jQuery对象,可以调用css方法:     $("div").eq(0).css("background","red");

对jQuery对象通过[0]取到的是原生的dom对象:    $("div")[0]     //不能调用jquery对象的方法

2.jquery对象和原生对象的互转

 2.1 原生dom对象=>jquery对象

        var domobj=document.querySelector("div");

        var jQueryObj1 = $(domobj);

2.2 jquery=>dom对象

          var domObj = $("div")[0];

          var domObj = $("div").get(0);//通过get()方法转换,eq()方法不可以

3.jQuery对象的增删改查方法

 // 增  末尾  append()

        $("body").append("123");

        $("body").append("<h1>123</h1>");

  // 预追加  prepend()

        $("body").prepend("<h1>前头</h1>");

    // $("") 可以创建元素      追加元素到哪个元素里面    appendTo()   prependTo()

        // appendTo 最佳到哪

        $("<h2>我是h2标签</h2>").appendTo("div");

        $("<h2>我是h2标签 开头</h2>").prependTo("div");

  // insertBefore  插入再某个元素之前

        // inserAfter插入再某个元素之后

        $("<h3>heloo </h3>").insertBefore("div");

        $("<h3>heloo </h3>").insertAfter("div");

//删除     删除当前元素   remove()

$("main").remove();

 //过滤删除

 // 删除所有p标签中的 拥有类名为.a的所有元素

    $("p").remove(".a");

清空子元素  自身依然存在  empty()

  // 查

        console.log(" ==== ",$("body"))

        // 无参均为查询

        console.log("======",$("div").text());

        // css 必须要传递参数 才为 查询

        console.log("======", $("div").css("color"));

each()属于jQuery提供的遍历方法

 $("div").each(function (index,el) {

            console.log(el);// 原生对象

            el.style.color = "red";

        })

要想使用foreach方法遍历须将jQuery用 toArray()或Array.from 把伪数组转化为数组对象

 $("div").toArray().forEach(element => {

            element.style.background = "blue";

           

        });

3.window对象的补充

 <button>警告框</button>

    <button>确认框</button>

    <button>提示框</button>


 

    <button>打开页面</button>

    <button>关闭页面</button>

    <!-- 仅在IE下有效果 -->

    <button>移动</button>

    <button>调整大小</button>


 

    <script>

   

        // 三个框子会阻止主线程的执行

        document.querySelectorAll("button")[0].onclick = function () {

            alert("警告框");

            console.log(123);

        }

        // confirm 确认

        document.querySelectorAll("button")[1].onclick = function () {

            var res = confirm("确认框"); // 有返回值 true or  false

        }

        document.querySelectorAll("button")[2].onclick = function () {

            var res = prompt("提示"); // 字符串

        }


 

        document.querySelectorAll("button")[3].onclick = function () {

            window.open("http://www.baidu.com","__blank","width=500,height=500");

        }

        document.querySelectorAll("button")[4].onclick = function () {

            window.close();

        }


    <!-- 仅在IE下有效果 -->

        document.querySelectorAll("button")[5].onclick = function () {

            window.moveBy(100,100);// 增量

            window.moveTo(100,100);// 到某个位置

           

        }

        document.querySelectorAll("button")[6].onclick = function () {

            window.resizeTo(100,100);// 调整窗口大小

        }

    </script>

4.图片的拖拽

遍历所有的img为其添加draggable=true的属性以及记录索引值的自定义属性index,并添加ondragstart事件,用中间变量selectImg记录当前拖拽的对象;给html元素添加ondragover事件并在其中阻止默认事件,以便ondrop事件的顺利执行;遍历所有的td为其添加记录索引值的自定义属性,添加ondrop事件,根据执行ondrop事件的对象的索引判断当前拖拽对象的索引是否与之匹配,如果匹配就将拖拽对象追加到对应的td中。

  var imgs = document.querySelectorAll("img");
        var tds = document.querySelectorAll("td");

        var selectImg = null;// 记录当前拖拽的对象

        for (let i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            img.index = i;
            img.draggable = true;
            img.ondragstart = function () {
                selectImg = this;
            }
        }

        for(let i = 0; i < tds.length;i++){
            var td = tds[i];
            td.index = i;
            td.ondrop = function () {
                if(this.index  === selectImg.index){
                    this.appendChild(selectImg);
                }
            }
        }

        document.documentElement.ondragover = function () {
            event.preventDefault();
        }

随机创建图片进行拖拽

要在随机创建图片的同时为其添加原来对应索引的自定义属性index,创建一个纯索引的数组,用随机数 取 数组中的一项 作为创建的图片时的路径值(+1)以及作为对应索引的自定义属性,在数组中去到一个后用splice()方法将其截掉,避免重复,将创建的img追加到div里,并添加ondragstar事件,用中间变量记录当前拖拽对象,同上再遍历td添加 ondrop事件,根据对应的自定义属性匹配对应的图片,将与之匹配的图片添加到其中。

   // 随机创建对应的图片
        // 7 3 4 2 1 5
        var array = [0,1,2,3,4,5,6,7];
        for(var i = 0;i < 8;i++){
            var img = document.createElement("img");
            var random = Math.floor(Math.random()*array.length);
            var value = array[random];
            img.dataset.index = value;
            array.splice(random,1);
            img.src = `images/${value+1}.png`;
            img.draggable = true;

            document.querySelector('.left').appendChild(img);
            img.ondragstart = function () {
                selectImg = this;
            }
        }
        var tds = document.querySelectorAll("td");
        var selectImg = null;// 记录当前拖拽的对象
        for(let i = 0; i < tds.length;i++){
            var td = tds[i];
            td.index = i;
            td.ondrop = function () {
               
                if(this.index  == selectImg.dataset.index){
                    this.appendChild(selectImg);
                }
            }
        }
        document.documentElement.ondragover = function () {
            event.preventDefault();
        }

5.瀑布流

瀑布流原理:每次将图片加在最小高度对应的列中

    var array = [10,8,20,3,2];

        var minValue = array[0];

        var minIndex = 0;

        for(let i = 1;i < array.length;i++){

            if(minValue > array[i]){

                minValue = array[i];

                minIndex = i;

            }

        }

        console.log(minIndex);

布局了一个大盒子里面五个等宽盒子横向布局,遍历数据源创建图片,在里面遍历五个盒子的高度,每次都找到最小高度对应的盒子将创建的图片追加其中。注意追加图片的时候要为图片设置宽高,只设置高不行,因为图片加载是异步的 ,执行时代码速度快于图片加载,

var divs = document.querySelectorAll(".box div");


        for (var i = 0; i < data.length; i++) {

            var minHeight = divs[0].offsetHeight; // 423 339  603  358  603
            var min = 0;
            console.log("===",divs[2].offsetHeight);

            var obj = data[i];
            divs.forEach((el, j) => {

                if (minHeight > el.offsetHeight) {
                    minHeight = el.offsetHeight;
                    min = j;
                }
            })
            var img = document.createElement("img");
            // 此处代码必须同时拥有宽高 
            // 欠一个问题   为什么会要必须添加宽度
            // 是因为图片加载是异步的   再执行时 代码速度快于图片加载,所以此时图片的宽度为0   再获取div的高度是 获取不到的
            img.style.width = "250px";
            img.style.height = obj.img_url.split("?")[1].split("x")[1] + "px";
            img.src = `${obj.img_url}`;
         
            divs[min].appendChild(img);

        }

6、购物车

全选:在全选的onchange事件中遍历所有的单选框,将全选框的选中状态赋给每一个单选框,在遍历时添加索引值,以便根据索引找到对应的对应商品的单价及数量,方便计算总价。

单行选中:遍历所有的单选框添加onchange事件,利用every()方法控制反选,遍历的时候也要添加索引值参数,方便找到对应的商品的单价和数量,判断单选框的选中状态,就让总价加上对应商品的总价,如果未选中就让总价减去对应商品的总价

点击+按钮的实现:遍历所有的+按钮为其添加onclick事件,也要传索引值参数,在事件中让对应的数量自增,然后判断对应的单选框是否为选中状态,若选中就让总价加上对应商品的单价。

点击-按钮的实现:同上,若选中,点击一次就让总价减去对应商品的单价一次。

        var str = "";
        for (var i = 0; i < 5; i++) {
            var good = goodList[i]
            str += `
            <tr>
                <td>
                    <input type="checkbox">
                </td>
                <td>
                    ${good.title}
                </td>
                <td>
                    <img src="${good.imageUrl}" alt="">
                </td>
                <td class='price'>
                    ${good.priceStr}
                </td>
                <td>
                    <button class="sub">-</button>
                    <span class='count'>1</span>
                    <button class="add">+</button>
                </td>
            </tr>
            
            `
        }
        table.innerHTML += str;

        var inputs = document.querySelectorAll("table input");
        inputs = Array.from(inputs);
        var priceArr = document.querySelectorAll(".price");
        var countArr = document.querySelectorAll(".count");
        var span = document.querySelector('.total');
        // 全选
        all.onchange = function () {
            var totalPrice = 0;
            inputs.forEach((el, i) => {
                el.checked = this.checked
                if (el.checked) {
                    totalPrice += priceArr[i].innerText * countArr[i].innerText;
                }
            });
            span.innerHTML = totalPrice;
        }

        // 单行

        inputs.forEach(function (input, index) {
            input.onchange = function () {
                all.checked = inputs.every(el => el.checked);
                var price = priceArr[index].innerText;
                var total = countArr[index].innerText;
                if (input.checked) {
                    span.innerHTML = span.innerHTML * 1 + price * total;
                }
                else {
                    span.innerHTML -= price * total;
                }
            }
        })
        // 加
        document.querySelectorAll(".add").forEach((btn, index) => {
            btn.onclick = function () {
                this.previousElementSibling.innerHTML++;
                if (inputs[index].checked) {
                   var price = priceArr[index].innerText;
                   span.innerHTML = span.innerHTML*1 + price * 1;
                }
            }
        })
        // 减逻辑
        document.querySelectorAll(".sub").forEach((el,index) => {
            el.onclick = function () {
                if (this.nextElementSibling.innerHTML == "1") return;
                this.nextElementSibling.innerHTML--;
                if (inputs[index].checked) {
                   var price = priceArr[index].innerText;
                   span.innerHTML = span.innerHTML*1 - price * 1;
                }
            }
        })

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值