JAVA程序员笔记(第二阶段:前端)第6篇——JavaScript粗略总结二

4 篇文章 0 订阅
本文涵盖了JavaScript中的核心概念,如原型、系统对话框、定时器、DOM操作等,并通过实例展示了如何实现日期格式化、鼠标跟随效果等功能。还探讨了JavaScript在处理URL、样式、事件监听等方面的应用,同时涉及到了JavaScript的零值特性以及setInterval与var关键字的差异。
摘要由CSDN通过智能技术生成

js-prototype原型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/commons.js"></script>
    <script>
        // 对日期做格式化 (JS 没有)

        // 如果 希望 Date 类 拥有 格式化日期的方法,则可以通过 prototype 原型 进行类的扩展

        // dir 方法可以显示数据


        console.log(Date.now());

        // 原型链Prototype 扩展的是该类的 对象共享的方法
        let date = new Date();

        console.log(date.format("hh:mm:ss E"));


        console.dir(Date)

        // console.log(Date.parse("2021-09-11 11:11:11.111"));


    </script>
</head>
<body>

</body>
</html>

js-系统对话框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        // alert(1)
        //
        // alert(2)

        /**
         *  confirm 传入的一个提示信息
         *
         *  confirm 返回一个 boolean 值,
         *
         *      点击确定返回 true . 点击取消返回 false
         *
         *  prompt 输入提示框
         *      可以传入 一个 提示 信息 和 输入框的默认值
         *
         *
         *     点击确定 返回 输入框中输入的内容
         *
         *     点击取消 返回 null
         *
         *
         */
        // console.log(confirm("您确定需要删除该条记录吗???"));

        console.log(prompt("请输入您的电话号码"))


    </script>
</head>
<body>
    <p>hello</p>
</body>
</html>

js-定时器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>


        console.log("aaaa")


        function a() {
            console.log("---2秒后才会执行的代码----")
        }

        // window.setTimeout(a, 1000) // 正确的写法
        // 编写一个定时器
       // window.setTimeout(a(), 1000) // 错误的写法

       // window.setTimeout("a()",  1000) // 正确的写法



      //  console.log(eval("1*2"));

        window.setTimeout(function a(){
            console.log("-------")
        }, 1000)



        console.log("over!!!")


    </script>
</head>
<body>

</body>
</html>

js-setInterval轮询

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        h1 {
            font-size: 100px;
            width: 350px;
            height:350px;
            text-align: center;
            margin: 100px auto 0;
        }

    </style>
    <script>

        function delay(){

            setTimeout(function() {
                delay()
            }, 1000)
        }

        delay()
       //  let count = 0 ;
       //  function a(){
       //      count ++ ;
       //      console.log("每间隔1秒执行一次")
       //
       //      if (count >= 10) {
       //          // 停止轮询
       //          clearInterval(playing)
       //
       //      }
       //  }
       //
       //  a()
       //
       // let playing = setInterval(a, 1000)

    </script>
</head>
<body>

    <h1 id="font">10</h1>

    <script>

        function randomRgb() {
            let r = Math.floor(Math.random() * 256)
            let g = Math.floor(Math.random() * 256)
            let b = Math.floor(Math.random() * 256)
            let a = (Math.random())
            return `rgba(${r}, ${g}, ${b}, ${a})`
        }
        // 获取到网页中的 h1 标签
        let h1 = document.getElementById("font");
        // 修改标签体中的内容
        // h1.innerText = 9
        let num = 10 ;

        let playing = setInterval(function(){

            h1.innerText = --num ;
            h1.style.color = randomRgb();
            h1.style.transition = `all .9s linear`

            if (num == 0) {
                h1.innerText = "OVER!" ;
                // 停止轮询
                clearInterval(playing)
            }

        }, 1000)


    </script>
</body>

</html>

+0和-0的区别

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var a = +0 ;

        var b = -0;

        //console.log(a === b)

        // Object.is 作用和 === 相似
        console.log(Object.is(a, b));//false

        console.log(NaN === NaN);//false

        console.log(isNaN(NaN));//true

        console.log(Object.is(NaN, NaN));//true


    </script>
</head>
<body>

</body>
</html>

setInterval和 var关键字

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        for(let i=0 ; i < 5; i++) {
            setTimeout(function(){
                console.log(i);
            }, 0)//小于0  默认等待1毫秒
        }


        //
        for(var i=0 ; i< 3; i++) {

            function xxx(i) {
                setTimeout(function(){
                    console.log(i);
                }, 0)
            }
            xxx(i);
        }

        console.log("先执行:");
        console.log(i);  // 3
        console.log("然后执行:");

    </script>
</head>
<body>

</body>
</html>

js-location解析网址

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 获取当前页面的网址
       let url =  window.location.href ;

       console.log(url)

       // 获取 网址的协议
        console.log(location.protocol);

       // 获取 主机名
        console.log(location.hostname);

        // 获取端口号
        console.log(location.port);

        // 获取请求路径
        console.log(location.pathname);

        // 获取 请求参数
        console.log(location.search);

        // 获取锚点
        console.log(location.hash);

        // 跳转到百度
        //window.location.href = "http://www.baidu.com"
        //window.location.assign("http://www.baidu.com")


        //window.location.replace("http://www.baidu.com")

        function goBaidu(){
            // 不会将原来的网址 记录到 历史记录中
            window.location.assign("https://www.bilibili.com/video/BV1GJ411x7h7/?spm_id_from=333.788.recommend_more_video.0")
        }
    </script>
</head>
<body>

    <a href="javascript:void(0)" onclick="goBaidu()">美女劲图</a>
</body>
</html>

js-dom-选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

    <div id="app">

        <p class="p1 icon">hello</p>
        <p class="p1">world</p>

        <p name="xxx" class="p2">over!!</p>

    </div>

    <script>
        // 获取 dom 元素,需要使用选择器

        // 常见的选择器 有
        /**
         *   标签选择器
         *
         *   document.getElementsByTagName("p")  // 获取所有 p 标签
         *
         *   ID选择器
         *   document.getElementById("id属性值")
         *
         *   类选择器
         *
         *   document.getElementsByClassName("class属性值")
         *
         *   name属性选择器
         *
         *   document.getElementByName("name属性值")
         *
         */

        // 返回的JS dom对象
        let tag = document.getElementById("app");

        console.log(tag)

        // 返回一个 形似数组的对象,可以使用 for...of 遍历
        let tags = document.getElementsByTagName("div")

        console.log(tags)

        // 获取 所有 class=p1 的元素
        let tags2 = document.getElementsByClassName("p1")

        console.log(tags2)

    </script>
</body>

</html>

js-dom元素操作标签体

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

  <div id="app">

    <p class="p1"><a href="#hello">hello</a></p>
    <p class="p1">world</p>

  </div>

  <script>

      // 选择 class=p1 的元素
      let tags = document.getElementsByClassName("p1");
      console.log(tags);

      // 获取 选中的 p 标签的 标签体中的内容
      for(let tag of tags) {

           // 获取标签体中的内容
          //console.log(tag.innerHTML);
         tag.innerHTML = "<b>我是动态的数据</b>"


            // 获取 标签体中的 纯文本内容
          //console.log(tag.innerText)
          tag.innerText = "<b>我是动态的数据</b>"
      }

  </script>

</body>
</html>

js-dom操作标签中的属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        function showText(tag) {

            // 获取输入框中输入的内容
            //let inp = document.getElementsByTagName("input")[0];


            //标签的内容  会赋值给标签的一个 value属性
            //也可以获取标签的value属性  来获得 标签体内容
            // 获取输入的内容
            console.log(tag.value);

        }

    </script>
</head>
<body>

<!--自定义属性 xx   -->
<div id="app" xx="tt">

    <p class="p1"><a href="#hello">hello</a></p>
    <p class="p1">world</p>

<!--
    输入框比较常用的事件 是 onchange(值改变且失去焦点)
    this 代表 当前事件 所在的 dom元素
 -->
    <input type="text" onchange="showText(this)" />

</div>

<script>

    // 使用 ID 选择器 选中 DIV
    let tag = document.getElementById("app") ;

    // console.log(tag.xx);    //这种写法不对。


    // 获取 div 的 ID 属性值
    //console.log(tag.xx)
    /**
     *
     *  getAttribute(key) : 根据属性名 获取属性值
     *
     *  setAttribute(key, val) : 设置(修改)属性
     *
     *  removeAttribute(key) : 删除某个属性
     *
     */
    console.log(tag.getAttribute("xx"));

    tag.setAttribute("yyyyy", "xxxx")

    tag.removeAttribute("id")


</script>

</body>
</html>

js-dom-操作 class样式 1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #star {
            width: 600px;
            height:40px;
            margin: 100px auto 0 ;
            font-size:28px;
        }

        .cur {
            color: #f00;
        }

    </style>
</head>
<body>

<div id="star">

    <span class="cur"></span>
    <span class="a"></span>
    <span class="a"></span>
    <span class="a"></span>
    <span class="a"></span>

</div>

<script>
    /**
     * 鼠标移入 对应的 心 染色
     *
     */
    // 获取 所有的星级 5个 span
    let spans = document.querySelectorAll("#star span") ;

    // 给 5个 span 绑定 鼠标 移入事件

    for(let i=0 ; i< spans.length; i++) {

        let tag = spans[i] ;

        // 给每一个 span 绑定 鼠标移入事件
        tag.addEventListener("mouseenter",  function(){
            // 写 触发事件的代码
            // 事件中 的 this 代表 事件的触发的源
            // console.log(this)
            // className会覆盖掉 原来的 class值
            //tag.className = "cur"


            // 添加样式 进行染色
            tag.classList.add("cur")

        })

        tag.addEventListener("mouseleave",  function(){
            // 写 触发事件的代码
            // 事件中 的 this 代表 事件的触发的源
            // console.log(this)
            // className会覆盖掉 原来的 class值
            //tag.className = "cur"

            // 添加样式 进行染色
            tag.classList.remove("cur")

        })

    }

</script>

</body>
</html>

js-dom-操作 class样式 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #star {
            width: 600px;
            height:40px;
            margin: 100px auto 0 ;
            font-size:28px;
        }

    </style>
</head>
<body>

<div id="star">

    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>

</div>

<script>
    /**
     * 鼠标移入 对应的 心 染色
     *
     */
    // 获取 所有的星级 5个 span
    let spans = document.querySelectorAll("#star span") ;

    // 给 5个 span 绑定 鼠标 移入事件

    for(let i=0 ; i< spans.length; i++) {

        let tag = spans[i] ;

        // 给每一个 span 绑定 鼠标移入事件
        tag.addEventListener("mouseenter",  function(){
            // 写 触发事件的代码
            // 事件中 的 this 代表 事件的触发的源
            // console.log(this)
            // className会覆盖掉 原来的 class值
            //tag.className = "cur"

            tag.style.color = "#f00"
            tag.style.backgroundColor = "#00f" // background-color

            // 添加样式 进行染色
            //tag.classList.add("cur")

        })

        tag.addEventListener("mouseleave",  function(){
            // 写 触发事件的代码
            // 事件中 的 this 代表 事件的触发的源
            // console.log(this)
            // className会覆盖掉 原来的 class值
            //tag.className = "cur"

            // 添加样式 进行染色
            //tag.classList.remove("cur")
            console.log("----")
            //delete tag.style.color

            // 移除 style属性
            this.removeAttribute("style")
        })
    }

</script>

</body>
</html>

js-dom-元素与元素之间的关系的获取方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

    <div id="app">
        <b>test</b>

        <p><a href="#">百度</a></p>

        <p>你好,世界</p>
    </div>

    <script>

        // 获取div 元素
       let div = document.querySelector("#app")

        // 获取该元素的所有子元素
        console.log(div.children);

        //console.log(div.childNodes);

        // 获取 div下的第一个 p 标签
        // :first-child等价与 :nth-child(1) 获取 父容器下的第一个子元素且子元素必须是 p 标签
        // :nth-child(n)
        // :nth-of-type 获取 父容器下的 指定满足条件的 某个元素
       let p = document.querySelector("#app p:nth-child(2)")

        console.log(p);

       // 获取 p 的父级元素
        console.log(p.parentNode);


        // 获取 当前 p 的上一个元素
        console.log(p.previousElementSibling);

        // 获取 当前 p 的下一个元素
        console.log(p.nextElementSibling);

    </script>

</body>
</html>

js-dom-元素位置属性

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

        #app {
            position: relative;
            width: 100px;
            height:100px;
            background-color: red;
        }

    </style>
</head>
<body>

<div id="app">


</div>

<script>

    // 获取div , querySelector 是从 IE9 开始支持
    let tag = document.querySelector("#app");

    // 获取 tag 的位置属性
    console.log(tag.offsetLeft);


</script>

</body>
</html>

js-dom-鼠标跟随效果

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

</body>
<script src="commons.js"></script>
<script>
    /**
     *
     * 实现鼠标跟随效果
     *
     *     addEventListener 绑定的事件,在回调函数中, 可以传入一个 event 事件对象作为参数
     *
     *     event.pageX  : 鼠标相对于 浏览器的水平偏移量
     *     event.pageY  : 鼠标相对于 浏览器的垂直偏移量
     *
     */
    //给鼠标加移动事件
    document.addEventListener("mousemove", function(event) {

        //console.log(event.pageX, event.pageY)

        // 在鼠标所在的位置,添加一个 小圆球
        // 动态创建一个 dom元素
        let dots = document.createElement("div");

        // 随机产生一个 4~ 11 之间的随机数
        let width = Math.floor(Math.random() * 15 + 10 )
        let height = width ;

        dots.style.position = "absolute";
        dots.style.width = `${width}px`;
        dots.style.height = `${height}px`;
        dots.style.backgroundColor = randomRgb();
        dots.style.left = event.pageX - width/2 + "px" ;
        dots.style.top = event.pageY - height/2 + "px" ;
        dots.style.borderRadius = "50%" ;
        dots.style.opacity = Math.random() ;
        console.log(dots)

        console.log(dots.style.width)

        document.body.append(dots)

        // 延迟 一段时候后, 删除 该 小球
        setTimeout(function(){
            // 删除dom
            dots.remove();
        }, 200)


    });

</script>

</html>

JS文件 日期格式化:

/**
 * 对日期进行格式化
 * 支持的模式有
 *      yyyy  年
 *      MM    月
 *      dd    日
 *      HH    24进制小时
 *      hh    12进制小时
 *      mm    分
 *      ss    秒
 *      SSS   毫秒
 *      E     星期
 *
 * @param pattern
 * @returns {string}
 */
Date.prototype.format = function (pattern = "yyyy-MM-dd HH:mm:ss") {
    //
    let year = this.getFullYear() + "";
    let month = this.getMonth() + 1 < 10 ? "0" + (this.getMonth() + 1) : this.getMonth() + 1;
    let date = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
    let hour = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
    let min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
    let sec = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
    let mill = (this.getMilliseconds() + "").padStart(3, "0");

    let weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
    let week = weekArray[this.getDay()]; // 0 ~6

    return pattern.replace("yyyy", year)
        .replace("MM", month)
        .replace("dd", date)
        .replace("HH", hour)
        .replace("hh", hour > 12 ? hour - 12 : hour)
        .replace("mm", min)
        .replace("ss", sec)
        .replace("SSS", mill)
        .replace("E", week)
}

/**
 * 获取 指定元素 到 浏览器的偏移量
 * @param target
 */
function getClientPos(target) {
    let left = 0, tops = 0;


    while (target.offsetParent) {

        left += target.offsetLeft + target.offsetParent.clientLeft;//距离边框的距离
        tops += target.offsetTop + target.offsetParent.clientTop;

        target = target.offsetParent;
    }

    return {left, tops}
}


function randomRgb() {
    let r = Math.floor(Math.random() * 256)
    let g = Math.floor(Math.random() * 256)
    let b = Math.floor(Math.random() * 256)
    return `rgb(${r}, ${g}, ${b})`
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值