IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> JAVA程序员笔记(第二阶段:前端)第8篇——JavaScript实现 轮播图 放大镜 本地存储cookie -> 正文阅读

[JavaScript知识库]JAVA程序员笔记(第二阶段:前端)第8篇——JavaScript实现 轮播图 放大镜 本地存储cookie

本次是轮播图的简单实现,往后会更新 最终版
补充昨天的snake:

/**
 *
 * new SnakeGame().start() 激活游戏
 *      按下 空格键 开始游戏
 *      按下 方向键 移动蛇
 *
 * @param position : 设置游戏的窗口位置 默认 relative
 * @param screenWidth : 设置游戏的容器的宽度 默认200, 单位 px
 * @param screenHeight : 设置游戏的容器的高度 默认 200, 单位 px
 * @param border : 设置游戏容器的边框  默认 5px solid lightblue
 * @param margin : 设置游戏容器的外边距 默认 是  0
 * @constructor
 *
 */
function SnakeGame({position="relative", screenWidth=200, screenHeight=200, border="5px solid lightblue", margin="0" } = {}) {

    // 存放蛇身体的每一部分
    this.snake = [];

    this.spWidth = 20 ;

    this.screenWidth = screenWidth ;
    this.screenHeight = screenHeight ;

    this.rows = this.screenHeight / this.spWidth;
    this.cols = this.screenWidth / this.spWidth;

    this.playing = false ;// 默认没有开始游戏

    this.position = position;

    this.margin = margin ;

    this.border = border ;

}

SnakeGame.prototype = {
    /**
     * 初始化游戏窗口
     */
    initGame() {
        this.screen = document.createElement("div");
        // 设置 舞台定位方式为相对定位
        this.screen.style.position = this.position ;
        this.screen.style.width = `${this.screenWidth}px`;
        this.screen.style.height = `${this.screenHeight}px`;
        this.screen.style.border = this.border ;
        this.screen.style.margin = this.margin ;
        this.screen.style.fontSize = "0";
        // 设置 600个 小的单元格

        for (let i = 0; i < this.rows; i++) {

            for (let j = 0; j < this.cols; j++) {
                // 创建一个 span 标签
                let span = document.createElement("span");
                // 将 span 设置为 行内块
                span.style.display = "inline-block";
                span.style.width = `${this.spWidth - 1}px`;
                span.style.height = `${this.spWidth - 1}px`;
                span.style.borderRight = "1px solid #ddd"
                span.style.borderBottom = "1px solid #ddd"
                // 初始化 前三个 span ,添加一个 class ="sk" 代表 上方有蛇
                if (i == 0 && j < 3) {
                    span.classList.add("sk")
                }
                this.screen.append(span);
            }
        }
        // 初始化 三个 蛇身,假设 p 表示蛇身
        for (let i = 0; i < 3; i++) {
            let p = document.createElement("p");
            p.style.position = "absolute";
            p.style.width = "20px";
            p.style.height = "20px";
            p.style.background = "#000";
            p.style.top = 0;
            p.style.left = i * 20 + "px";

            // unshift 添加元素,保证最后的p 是蛇头
            this.snake.unshift(p);
            this.screen.appendChild(p);

        }

        // 随机生成 食物
        this.randomFood();

        //console.log(this.snake)

        this.spans = this.screen.querySelectorAll("span")

        document.body.appendChild(this.screen);
    },
    /**
     * 生成食物
     */
    randomFood() {
        // 获取 没有蛇的所有 span
        let spans = this.screen.querySelectorAll("span:not(.sk)");
        // console.log(spans)
        // 随机产生一个 0 ~ spans.length 的 索引
        let index = Math.floor(Math.random() * spans.length)

        // 获取随机产生的 span
        let span = spans[index];

        //console.log(span)
        // 动态创建一个 b 标签
        let tag = document.createElement("b");
        tag.style.display = "block";
        tag.style.width = "10px"
        tag.style.height = "10px";
        tag.style.margin = "5px";
        tag.style.backgroundColor = "#f00"
        tag.style.borderRadius = "50%"

        // 将生成的 b标签,添加到 span 中
        span.appendChild(tag);
    },
    /**
     * 开始游戏
     */
    start() {
        // 初始化游戏
        this.initGame();

        // 按下空格键,开始游戏 (绑定键盘事件)
        document.addEventListener("keydown", (event) => {
            // event.keyCode 获取按下的按键编码
            if (event.keyCode == 32 && !this.playing) {

                this.dir = "right"; // 默认方向

                // 开始游戏
                this.playing = setInterval(()=>{

                    // 获取 当前蛇头的位置
                    let sk = this.snake[0];

                    // 获取 距离父元素的位置
                    let left = sk.offsetLeft;
                    let tops = sk.offsetTop;

                    if (this.dir === "right") {
                        left += 20;
                    } else if (this.dir === "left") {
                        left -= 20;
                    } else if (this.dir === "top") {
                        tops -= 20;
                    } else if (this.dir === "down") {
                        tops += 20;
                    }
                    this.addSnake(left, tops)

                }, 300)
            } else if(this.playing && event.keyCode == 37 && this.dir !="right"){
                this.dir = "left";
            }else if(this.playing && event.keyCode == 38  && this.dir !="down"){
                this.dir = "top";
            }else if(this.playing && event.keyCode == 39  && this.dir !="left"){
                this.dir = "right";
            }else if(this.playing && event.keyCode == 40  && this.dir !="top"){
                this.dir = "down";
            }

        })

    },
    /**
     * 获取指定偏移量对应的索引位置
     */
    getIndex(left, tops) {

        let x = left/this.spWidth ;
        let y = tops/this.spWidth;

        return y * this.cols + x ;
    },
    /**
     * 结束游戏
     */
    gameOver() {
        alert("/(ㄒoㄒ)/~~GAME OVER!!!");
        // 停止轮询
        clearInterval(this.playing);

        // 游戏初始化
        // 删除舞台
        this.screen.remove();

        this.snake = [] ;
        this.playing = false ;
        this.dir = "right";

        // 初始化舞台
        this.initGame() ;
    },
    /**
     * 添加蛇头
     */
    addSnake(left, tops) {

        // 判断 蛇头是否超出了边界
        if (left >= this.screen.clientWidth || left <0 || tops < 0 || tops >= this.screen.clientHeight) {
            this.gameOver();
            return ;
        }


        // 生成一个 p 标签
        let p = document.createElement("p");
        p.style.position = "absolute";
        p.style.width = `${this.spWidth}px`;
        p.style.height = `${this.spWidth}px`;
        p.style.background = "#000";
        p.style.top = tops + "px";
        p.style.left = left + "px";


        // 找到 新添加的 蛇头对应的 span, 添加一个 class = "sk"
        // 获取 span
        let index = this.getIndex(left, tops)
        let span = this.spans[index];

        // 判断 该 span 上是否有食物
        let b = span.querySelector("b")

        if (b ==null) { // 没有食物,删除蛇尾
            // 移除蛇尾
            let p2 = this.snake.pop()
            left = p2.offsetLeft ;
            tops = p2.offsetTop ;

            index = this.getIndex(left, tops)
            let span2 = this.spans[index];
            span2.classList.remove("sk")
            // 从屏幕中移除蛇尾
            p2.remove();
        }

        // 判断 蛇头出现的位置上是否右 sk
        if (span.classList.contains("sk")) {
            this.gameOver();
            return ;
        }
        // 将蛇头
        span.classList.add("sk")
        // unshift 添加元素,保证最后的p 是蛇头
        this.snake.unshift(p);
        this.screen.appendChild(p);

        if(b !=null) { //
            b.remove();
            // 随机产生新食物
            this.randomFood();
        }

    }
}

js-轮播图的实现

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

        ul {
            list-style: none
        }

        .swiper {
            position: relative;
            width: 960px;
            height: 460px;
            margin: 50px auto 0;
            /*background-color: red;*/
        }

        .swiper img {
            position: absolute;
            width: 100%;
            height: 100%;
            display: none; /* 四张图片全部隐藏*/
        }

        .swiper img:first-child {
            display: block;
        }

        .swiper .dots {
            position: absolute;
            height: 40px;
            width: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            bottom: 0px;
            text-align: center;
            font-size: 0;
        }

        .swiper .dots span {
            display: inline-block;
            width: 10px;
            height: 10px;
            background-color: snow;
            margin: 15px 5px;
            border-radius: 50%;

        }

        .swiper .dots .cur {
            background-color: red;
        }

        .swiper .left, .swiper .right {
            position: absolute;
            width: 40px;
            height: 70px;
            background: url("./images/icon-slides.png") no-repeat;
            top: 210px;
            cursor: pointer;
        }

        .swiper .right {
            right: 0px;
            background-position: -43px 0;
        }

        .swiper .left:hover {
            background-position: -85px 0;
        }

        .swiper .right:hover {
            background-position: -128px 0;
        }

        /**
        淡出
         */
        @keyframes fadeOut {
            to {
                transform: translateX(-960px);
                height: 100px;
                margin: 150px 0;
                opacity: 0;
            }
        }

        /**
        淡入
         */
        @keyframes fadeIn {
            from {
                transform: translateX(-960px);
                height: 0px;
                width: 0px;
                opacity: 0;
            }
            to {
                transform: translateX(0);
                height: 400px;
                width: 960px;
                opacity: 1;
            }
        }


    </style>
</head>
<body>
<div class="swiper">

    <img class="cur" src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/a532e33470d046b3f044d5ea49fc5e9e.png?thumb=1&w=1226&h=460&f=webp&q=90"/>
    <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/918820682e4a490221cfd92b24c14b86.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
    <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/67c7222fbcf98db942718eaf29f32297.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
    <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/01a5d7313fe344bddb9e4081df4dc998.jpg?w=2452&h=920"/>

    <div class="dots">
        <span class="cur"></span>
        <span></span>
        <span></span>
        <span></span>
    </div>

    <div class="left"></div>
    <div class="right"></div>

</div>


<script>
    /**
     *显示index图片  index从0开始
     *
     */
    function showImg(index) {

        //获取 原来原来显示的图片 > 表示 子选择器
        let img = document.querySelector(".swiper > .cur");
        let target = document.querySelector(`.swiper img:nth-of-type(${index + 1})`);

        // 添加淡入动画
        target.style.animation = "fadeIn 1s";
        // 给 img 添加动画
        img.style.animation = "fadeOut 1s" ;

        // 目标图片必须先显示,否则 无法对 动画完成进行 监控
        target.style.display = "block";
        // 监听动画完成
        target.addEventListener("animationend",function (){
            // 删除 target 的 style 属性
            target.removeAttribute("style");
            // 将原来的图片进行隐藏
            target.style.display = "block" ;
            target.classList.add("cur");
        })

        img.addEventListener("animationend",function (){
            // 删除 img 的 style 属性
            img.removeAttribute("style");
            // 将原来的图片进行隐藏
            img.style.display = "none";
            img.classList.remove("cur");

        })

        //获取原来的带有cur的点
        document.querySelector(".swiper .dots .cur").classList.remove("cur")

        document.querySelector(`.swiper .dots span:nth-of-type(${index + 1})`).classList.add("cur")

    }


    //代表默认显示第一张
    let index = 0;
    //获取图片个数
    let len = document.querySelectorAll(".swiper img").length;

    // 图片下翻
    document.querySelector(".swiper .right").addEventListener("click", function (event) {

        if (index == len - 1) {
            index = -1;
        }
        showImg(++index);

    })

    // 图片上翻
    document.querySelector(".swiper .left").addEventListener("click", function (event) {

        if (index == 0) {
            index = len;
        }
        showImg(--index);

    })

    //获取这几个图的标签
    let dots = document.querySelectorAll(".swiper .dots span")


    /**
     * 事件委托机制
     *  给 div/dots 绑定单击事件
     *
     *     1.减少事件的绑定次数
     *     2.可以给未来会出现的元素  绑定事件
     */

    document.querySelector(".swiper .dots").addEventListener("click", function (event) {
        //event.target  获取被委托的元素,  代表 事件触发的源对象
        if (event.target.tagName == "SPAN") {

            //获取对应的 span 的索引
            index = Array.from(dots).findIndex(s => s === event.target)

            showImg(index);
        }
    })

    //默认playing为false
    let playing = false;

    /**
     * 自动播放
     */

    function autoPlay() {
        /**
         * 轮播图2s播放一张
         */
        playing = setInterval(function () {

            //自动调用 下一张
            document.querySelector(".swiper .right").dispatchEvent(new MouseEvent("click"));

        }, 2000);
    }

    function stopPlay(){
        clearInterval(playing);
    }
    /**
     * 给整个轮播图 添加一个 mouseover ( 停止自动播放) , mouseout (自动播放)
     */
    document.querySelector(".swiper").addEventListener("mouseover",stopPlay);
    document.querySelector(".swiper").addEventListener("mouseout",autoPlay);

    autoPlay();


</script>

</body>
</html>

——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

js-全选效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="checkbox" name="" id="all">全选
<hr/>
<div id="hobby">
    <input type="checkbox" name="" value="游泳">游泳
    <input type="checkbox" name="" value="爬山">爬山
    <input type="checkbox" name="" value="学JAVA">JAVA
    <input type="checkbox" name="" value="旅游">旅游
</div>

<p>
    您选择的爱好有:<b id="res">[]</b>
</p>

<script>
    /**
     * 复选框 / 单选框 一般用 change 事件
     */
        // 存储爱好
    let hobbies = [];

    document.querySelector("#all").addEventListener("change", function () {

        //获取下面四个复选框
        //属性选择器 [type = checkbox]
        let tags = document.querySelectorAll("#hobby input[type = checkbox]");

        //遍历每一个 爱好复选框
        //然后将复选框的checked 属性修改成 all复选框的值
        for (let tag of tags) {
            tag.checked = this.checked;

            if (this.checked) {
                hobbies.push(tag.value);
            }
        }
        if (this.checked) {
            document.querySelector("#res").innerText = `[${hobbies}]`;
        } else {//爱好清空
            hobbies = [];
            document.querySelector("#res").innerText = `[]`;
        }

    })

    document.querySelector("#hobby").addEventListener("change", function (event) {

        //代理
        if (event.target.nodeName === "INPUT") {

            // 获取被 勾选的 input  :checked 获取被勾选的元素
            let len = this.querySelectorAll(":checked").length;

            let ck = len === this.children.length;

            document.querySelector("#all").checked = ck;

            let status = event.target.checked;

            if (status) {
                hobbies.push(event.target.value);
            } else {
                //
                let index = hobbies.indexOf(event.target.value);
                hobbies.splice(index, 1);
            }
            // 设置选中的爱好
            document.querySelector("#res").innerText = `[${hobbies}]`;
        }
    })

</script>

</body>
</html>

js-阻止元素的默认行为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /**
         *  a 标签 href 在单击后 自动跳转到 指定页面
         *
         *  textarea 按下回车 默认换行
         *
         *  form 表单 和 submit 按钮 配合 会自动提交表单
         *
         */

        /**
         * 第一种阻止默认行为的方式
         *      1. 事件对应的 函数 return false
         *      2. 在 onclick 事件绑定上, 添加return 关键字
         *
         *  本质是 在 事件上 return false 即可阻止默认行为
         *
         */
        function goQQ() {

            // console.log("+++++++++")
            window.location.href = "https://www.qq.com"

            return false ;
        }

        /**
         *  通过 event 事件对象, 阻止 元素默认行为
         */
        // function goBaidu() {
        //     window.location.href = "https://www.baidu.com"
        //
        //     // 阻止默认行为
        //     window.event.preventDefault() ;
        //
        // }
    </script>
</head>
<body>

    <a href="https://www.baidu.com" onclick="return goQQ()">百度</a>

    <a href="https://www.sina.com" id="sina">新浪</a>

    <script>

        document.querySelector("#sina").addEventListener("click", function(event){
            window.location.href = "https://www.baidu.com";
            event.preventDefault() ;
        })

    </script>
</body>
</html>

js-滚动轮播图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #swiper {
            position: relative;
            width: 960px;
            height:400px;
            margin:100px auto 0 ;
            font-size: 0;
        }

        #swiper .images {
            position: absolute;
            width: 100%;
            height:100%;
            white-space: nowrap;
            overflow: hidden; /*不显示*/
        }

        #swiper img {
            width: 100%;
            height: 100%;
        }
        #swiper .dots {
            position: absolute;
            height: 40px;
            bottom: 0px;
            background-color: rgba(0, 0, 0, 0.6);
            width: 100%;
            font-size: 0;
            text-align: center;
        }

        #swiper .dots span {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #fff;
            margin: 15px 5px;
            cursor: pointer;
        }

        #swiper .dots .cur {
            background-color: red;
        }

        #swiper .left, #swiper .right {
            position: absolute;
            width: 42px;
            height: 70px;
            background: url(./images/icon-slides.png) no-repeat -84px 0;
            top: 165px;
            cursor: pointer;
        }

        /*调雪碧图*/
        #swiper .right {
            right: 0px;
            background-position: -126px 0;
        }

        #swiper .left:hover {
            background-position: 0 0;
        }

        #swiper .right:hover {
            background-position: -42px 0;
        }


    </style>
</head>
<body>

    <div id="swiper">

        <div class="images">
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/a532e33470d046b3f044d5ea49fc5e9e.png?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/918820682e4a490221cfd92b24c14b86.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/67c7222fbcf98db942718eaf29f32297.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/01a5d7313fe344bddb9e4081df4dc998.jpg?w=2452&h=920"/>
        </div>

        <div class="dots">
            <span class="cur"></span>
            <span></span>
            <span></span>
            <span></span>
        </div>

        <div class="left"></div>
        <div class="right"></div>

    </div>

    <script>
        let swiper = document.querySelector("#swiper");
        let img = document.querySelector("#swiper .images");
        //克隆第一张图  添加到最后
        let last = img.querySelector("img").cloneNode();
        img.appendChild(last);

        let lastTime  = null;//最后点击的时间
        let counterTime = 1000;//限制的时间

        document.querySelector("#swiper .right").addEventListener("click",function (event){
            let count = 0;

            //节流  防止点太快
            let now = new Date().getTime();

            if(lastTime != null){
                if(now - lastTime < counterTime )return;
            }
            lastTime = now;


            let playing = setInterval(function (){
                count ++ ;

                // 每点击一次,将水平滚动条 向右 拖动 960px
                img.scrollLeft = img.scrollLeft + swiper.clientWidth / 10 ;

                if (count >= 10) {
                    clearInterval(playing);

                    // 判断 滚动条的位置是否在 最右边,如果是,则快速将滚动条切换到 0

                    if (img.scrollLeft >= (img.querySelectorAll("img").length - 1) * swiper.clientWidth) {
                        img.scrollLeft = 0 ;
                    }
                    // 获取 滚动条的位置
                    let index = img.scrollLeft / swiper.clientWidth ;

                    // 给 指定索引位置的span 添加样式
                    document.querySelector("#swiper .dots .cur").classList.remove("cur");
                    document.querySelector(`#swiper .dots span:nth-of-type(${index + 1})`).classList.add("cur")

                }
            },100)


        })


    </script>

</body>
</html>

js-滚动轮播图-下翻

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #swiper {
            position: relative;
            width: 960px;
            height:400px;
            margin:100px auto 0 ;
            font-size: 0;
        }

        #swiper .images {
            position: absolute;
            width: 100%;
            height:100%;
            white-space: nowrap;
            overflow: scroll hidden;
        }

        #swiper img {
            width: 100%;
            height: 100%;
        }
        #swiper .dots {
            position: absolute;
            height: 40px;
            bottom: 0px;
            background-color: rgba(0, 0, 0, 0.6);
            width: 100%;
            font-size: 0;
            text-align: center;
        }

        #swiper .dots span {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #fff;
            margin: 15px 5px;
            cursor: pointer;
        }

        #swiper .dots .cur {
            background-color: red;
        }

        #swiper .left, #swiper .right {
            position: absolute;
            width: 42px;
            height: 70px;
            background: url(./images/icon-slides.png) no-repeat -84px 0;
            top: 165px;
            cursor: pointer;
        }

        #swiper .right {
            right: 0px;
            background-position: -126px 0;
        }

        #swiper .left:hover {
            background-position: 0 0;
        }

        #swiper .right:hover {
            background-position: -42px 0;
        }


    </style>
</head>
<body>

    <div id="swiper">

        <div class="images">
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/a532e33470d046b3f044d5ea49fc5e9e.png?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/918820682e4a490221cfd92b24c14b86.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/67c7222fbcf98db942718eaf29f32297.jpg?thumb=1&w=1226&h=460&f=webp&q=90"/>
            <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/01a5d7313fe344bddb9e4081df4dc998.jpg?w=2452&h=920"/>

        </div>

        <div class="dots">
            <span class="cur"></span>
            <span></span>
            <span></span>
            <span></span>
        </div>

        <div class="left"></div>
        <div class="right"></div>
    </div>

    <script>
        let swiper = document.querySelector("#swiper");
        let img = document.querySelector("#swiper .images");

        // 克隆 第一张图片,并追加到 第四章图片的 后面
        let last = img.querySelector("img").cloneNode();

        //console.log(last)
        img.appendChild(last);

        document.querySelector("#swiper .right").addEventListener("click", function(event){
            let count = 0 ;

            let playing = setInterval(function(){
                count ++ ;

                // 每点击一次,将水平滚动条 向右 拖动 960px
                img.scrollLeft = img.scrollLeft + swiper.clientWidth / 10 ;

                if (count >= 10) {
                    clearInterval(playing);

                    // 判断 滚动条的位置是否在 最右边,如果是,则快速将滚动条切换到 0

                    if (img.scrollLeft >= (img.querySelectorAll("img").length - 1) * swiper.clientWidth) {
                        img.scrollLeft = 0 ;
                    }
                    // 获取 滚动条的位置
                    let index = img.scrollLeft / swiper.clientWidth ;

                    // 给 指定索引位置的span 添加样式
                    document.querySelector("#swiper .dots .cur").classList.remove("cur");
                    document.querySelector(`#swiper .dots span:nth-of-type(${index + 1})`).classList.add("cur")

                }
            }, 100)


        })




    </script>
</body>
</html>

js-事件冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    #app {
      width: 300px;
      height: 300px;
      background-color: red;
      /*border: 2px solid green;*/
      overflow: hidden; /* ... */
    }

    #inner {
      width: 150px;
      height: 150px;
      margin: 75px;
      background-color: blue;
    }

  </style>
</head>
<body>

    <div id="app">

      <div id="inner"></div>

    </div>

    <script>

      document.querySelector("#app").addEventListener("click", function(event) {
        console.log("app... 被点击")
      })


      document.querySelector("#inner").addEventListener("click", function(event) {
        console.log("inner... 被点击")

        // Propagation (传播特性)
        event.stopPropagation();
       // event.cancelBubble = true;
      })


    </script>

</body>
</html>

js-事件捕获

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #app {
            width: 300px;
            height: 300px;
            background-color: red;
            /*border: 2px solid green;*/
            overflow: hidden; /* ... */
        }

        #inner {
            width: 150px;
            height: 150px;
            margin: 75px;
            background-color: blue;
        }

    </style>
</head>
<body>
<div id="app">

    <div id="inner"></div>

</div>

<script>
    /**
     *   JS 事件 默认采用的是 事件冒泡 机制
     *
     *   JS 如果需要使用 事件捕获机制 ,则 可以在 使用 addEventListener进行事件绑定的时候,进行特殊设置 即可
     *
     */

    document.querySelector("#app").addEventListener("click", function (event) {
        console.log("app... 被点击")

        event.stopPropagation()

    }, true)


    document.querySelector("#inner").addEventListener("click", function (event) {
        console.log("inner... 被点击")


    }, true)


</script>

</body>
</html>

js-load事件

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

    <script>

        function test() {
            alert(alert)
        }

        // DOM加载完成后,才会触发的代码
        // 一个 网页只能绑定 一次 onload

        //window.onload = test ;

    </script>

</head>
<body onload="test()">
    <p>hello</p>
    <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/01a5d7313fe344bddb9e4081df4dc998.jpg?w=2452&h=920" />

</body>
</html>

js-放大镜

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #zoom {
            position: relative;
            width: 500px;
            height:500px;
            margin: 100px auto 0 ;
        }

    </style>
    <script src="js/commons.js"></script>
</head>
<body>
    <div id="zoom">
        <img src="./images/放大镜.png" width="400px"/>
    </div>


    <script>

        let img = document.querySelector("#zoom img")

        // 放大
        img.zoom();

    </script>

</body>
</html>

js-本地存储-cookie

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

        //setCookie("xxx", "vvvvv")
        //
        console.log(getCookie("xxx"));

        removeCookie("xxx")

       // localStorage.setItem("xxxx", "vvvvvvvv");

        console.log(localStorage.getItem("xxxx"));


       // sessionStorage.setItem("xxxxx", "yyyyyyyyyyyyyyy");

        console.log(sessionStorage.getItem("xxxxx"));


    </script>
</head>
<body>

</body>
</html>

.js文件

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}
}

/**
 * 图片放大镜的方法
 */
HTMLImageElement.prototype.zoom = function () {

    // this 代表 img 对象
    // 给 img 图片设置一个 小正方形, 正方形的边长 = 图片所在容器的 宽/高(最小值) 除以2
    let minBorder = this.clientWidth > this.clientHeight ? this.clientHeight : this.clientWidth;
    // 获取小正方形的宽和高
    let wh = Math.floor(minBorder / 2);


    // 创建一个 div容器,用来 存放 放大后的图片
    let zoomDiv = document.createElement("div");

    zoomDiv.style.position = "absolute" ;
    zoomDiv.style.left = this.offsetLeft + this.offsetWidth + "px" ;
    zoomDiv.style.top = this.offsetTop + "px" ;



    // 将 zoomDiv 追加到 图片父元素的里面
    this.parentNode.appendChild(zoomDiv);


    let that = this;

    this.parentNode.addEventListener("mousemove", function (event) {

        // 获取 图片距离浏览器的距离
        let {left, tops} = getClientPos(that);

        let {left: pLeft, tops: pTop} = getClientPos(this);

        // 计算鼠标是否在 图片所在的区域上
        if (event.pageX - left >= 0 && event.pageX - left <= that.clientWidth &&
            event.pageY - tops >= 0 && event.pageY - tops <= that.clientHeight) {
            zoomDiv.style.display = "block" ;
            if (this.model == null) {
                // 创建一个 div 小正方形块
                let model = document.createElement("div");
                model.style.width = wh + "px";
                model.style.height = wh + "px";
                model.style.background = "rgba(200, 200, 200, 0.4)";
                model.style.position = "absolute";
                model.style.cursor = "move";

                this.model = model;
                // 将 小正方形块 和 img 做成兄弟元素
                this.appendChild(model);

                // 给 块绑定一个鼠标移除事件
                model.addEventListener("mouseout", e=>{
                    model.remove();
                    this.model = null ;
                    zoomDiv.style.display = "none";
                })

            }

            let offsetLeft = event.pageX - this.model.offsetWidth / 2 - pLeft;
            let offsetTop = event.pageY - this.model.offsetHeight / 2 - pTop;

            //console.log("xxx")
            this.model.style.left = offsetLeft + "px";
            this.model.style.top = offsetTop + "px";

            // 限制 小方块的移动范围,只能在图片中 , 说明 小方块超出了 左边界
            if (this.model.offsetLeft < that.offsetLeft) {
                this.model.style.left = that.offsetLeft + "px";
            }
            // 说明超出了右边界
            if (that.offsetLeft + that.offsetWidth - that.clientLeft - this.model.clientWidth < this.model.offsetLeft) {
                this.model.style.left = that.offsetLeft + that.offsetWidth - that.clientLeft - this.model.clientWidth + "px"
            }

            if (this.model.offsetTop < that.offsetTop) {
                this.model.style.top = that.offsetTop + "px";
            }

            if (that.offsetTop + that.offsetHeight - that.clientTop - this.model.clientHeight < this.model.offsetTop) {
                this.model.style.top = that.offsetTop + that.offsetHeight - that.clientTop - this.model.clientHeight + "px"
            }


            // 通过 小方块在在 img 图中的位置, 计算 在高清图中的位置

            let rx = this.model.offsetLeft - that.offsetLeft ;
            let ry = this.model.offsetTop - that.offsetTop ;

            // 获取 图片原始宽高
            let image = new Image() ;
            image.src = that.src ;

            // 当图片加载完成后,获取图片原始宽高
            image.onload = function() {

                // 获取 图片的宽高
                let w = this.width ;
                let h = this.height ;

                // 获取 小方块左上角 在高清图中的位置
                let x = rx / that.clientWidth * w ;
                let y = ry / that.clientHeight * h ;

                // 获取放大的容器的宽度 和 高度
                let zw = wh / that.clientWidth * w ;
                let zh = wh / that.clientHeight * h ;

                // 设置放大镜的宽和高
                zoomDiv.style.width = zw + "px" ;
                zoomDiv.style.height = zh + "px";

                // 设置背景图
                zoomDiv.style.backgroundImage = `url(${this.src})` ;
                zoomDiv.style.backgroundRepeat = "no-repeat";
                // 设置背景图
                zoomDiv.style.backgroundPosition = `-${x}px -${y}px` ;

            }
        }

    })

}


commons.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})`
}


/**
 * 图片放大镜的方法
 */
HTMLImageElement.prototype.zoom = function () {

    // this 代表 img 对象
    // 给 img 图片设置一个 小正方形, 正方形的边长 = 图片所在容器的 宽/高(最小值) 除以2
    let minBorder = this.clientWidth > this.clientHeight ? this.clientHeight : this.clientWidth;
    // 获取小正方形的宽和高
    let wh = Math.floor(minBorder / 2);


    // 创建一个 div容器,用来 存放 放大后的图片
    let zoomDiv = document.createElement("div");

    zoomDiv.style.position = "absolute" ;
    zoomDiv.style.left = this.offsetLeft + this.offsetWidth + "px" ;
    zoomDiv.style.top = this.offsetTop + "px" ;



    // 将 zoomDiv 追加到 图片父元素的里面
    this.parentNode.appendChild(zoomDiv);


    let that = this;

    this.parentNode.addEventListener("mousemove", function (event) {

        // 获取 图片距离浏览器的距离
        let {left, tops} = getClientPos(that);

        let {left: pLeft, tops: pTop} = getClientPos(this);

        // 计算鼠标是否在 图片所在的区域上
        if (event.pageX - left >= 0 && event.pageX - left <= that.clientWidth &&
            event.pageY - tops >= 0 && event.pageY - tops <= that.clientHeight) {
            zoomDiv.style.display = "block" ;
            if (this.model == null) {
                // 创建一个 div 小正方形块
                let model = document.createElement("div");
                model.style.width = wh + "px";
                model.style.height = wh + "px";
                model.style.background = "rgba(255, 255, 0, 0.6)";
                model.style.position = "absolute";
                model.style.cursor = "move";

                this.model = model;
                // 将 小正方形块 和 img 做成兄弟元素
                this.appendChild(model);

                // 给 块绑定一个鼠标移除事件
                model.addEventListener("mouseout", e=>{
                    model.remove();
                    this.model = null ;
                    zoomDiv.style.display = "none";
                })

            }

            let offsetLeft = event.pageX - this.model.offsetWidth / 2 - pLeft;
            let offsetTop = event.pageY - this.model.offsetHeight / 2 - pTop;

            //console.log("xxx")
            this.model.style.left = offsetLeft + "px";
            this.model.style.top = offsetTop + "px";

            // 限制 小方块的移动范围,只能在图片中 , 说明 小方块超出了 左边界
            if (this.model.offsetLeft < that.offsetLeft) {
                this.model.style.left = that.offsetLeft + "px";
            }
            // 说明超出了右边界
            if (that.offsetLeft + that.offsetWidth - that.clientLeft - this.model.clientWidth < this.model.offsetLeft) {
                this.model.style.left = that.offsetLeft + that.offsetWidth - that.clientLeft - this.model.clientWidth + "px"
            }

            if (this.model.offsetTop < that.offsetTop) {
                this.model.style.top = that.offsetTop + "px";
            }

            if (that.offsetTop + that.offsetHeight - that.clientTop - this.model.clientHeight < this.model.offsetTop) {
                this.model.style.top = that.offsetTop + that.offsetHeight - that.clientTop - this.model.clientHeight + "px"
            }


            // 通过 小方块在在 img 图中的位置, 计算 在高清图中的位置

            let rx = this.model.offsetLeft - that.offsetLeft ;
            let ry = this.model.offsetTop - that.offsetTop ;

            // 获取 图片原始宽高
            let image = new Image() ;
            image.src = that.src ;

            // 当图片加载完成后,获取图片原始宽高
            image.onload = function() {

                // 获取 图片的宽高
                let w = this.width ;
                let h = this.height ;

                // 获取 小方块左上角 在高清图中的位置
                let x = rx / that.clientWidth * w ;
                let y = ry / that.clientHeight * h ;

                // 获取放大的容器的宽度 和 高度
                let zw = wh / that.clientWidth * w ;
                let zh = wh / that.clientHeight * h ;

                // 设置放大镜的宽和高
                zoomDiv.style.width = zw + "px" ;
                zoomDiv.style.height = zh + "px";

                // 设置背景图
                zoomDiv.style.backgroundImage = `url(${this.src})` ;
                zoomDiv.style.backgroundRepeat = "no-repeat";
                // 设置背景图
                zoomDiv.style.backgroundPosition = `-${x}px -${y}px` ;

            }
        }

    })

}


  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-10-19 11:47:14  更:2021-10-19 11:48:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/13 13:57:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码