JavaScript 入门案例

时间:2022-11-07 12:01:20

四、  JavaScript 入门案例

在看本节之前,笔者建议您先看 JavaScript 基础篇  https://www.cnblogs.com/IT-LFP/p/10945884.html

1.  瀑布流

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>布局-瀑布流</title>

    <link rel="stylesheet" href="css/layout.css" />
    <script src="js/layout.js"></script>
</head>
<body>
<div id="container">
    <div class="box">
        <div class="box_img">
            <a href="img/1.jpg"><img src="img/1.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/2.jpg"><img src="img/2.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/3.jpg"><img src="img/3.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/4.jpg"><img src="img/4.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/5.jpg"><img src="img/5.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/6.jpg"><img src="img/6.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/7.jpg"><img src="img/7.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/8.jpg"><img src="img/8.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/9.jpg"><img src="img/9.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/10.jpg"><img src="img/10.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/11.jpg"><img src="img/11.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/12.jpg"><img src="img/12.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/13.jpg"><img src="img/13.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/14.jpg"><img src="img/14.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/15.jpg"><img src="img/15.jpg" alt="" ></a>
        </div>
    </div>
    <div class="box">
        <div class="box_img">
            <a href="img/6.jpg"><img src="img/16.jpg" alt="" ></a>
        </div>
    </div>
</div>
</body>
<script>
window.onload = function () {
    imgLocation("container", "box");
    var imgData = {
        "data": [
            {"src": "2.jpg"}, {"src": "4.jpg"}, {"src": "6.jpg"}, {"src": "8.jpg"}, {"src": "10.jpg"}, {"src": "12.jpg"}, {"src": "14.jpg"}, {"src": "16.jpg"},
            {"src": "1.jpg"}, {"src": "3.jpg"}, {"src": "5.jpg"}, {"src": "7.jpg"}, {"src": "9.jpg"}, {"src": "11.jpg"}, {"src": "13.jpg"}, {"src": "15.jpg"}
        ]
    };
    window.onscroll = function () {
        if (checkFlag()) {
            var cparent = document.getElementById("container");
            for (var i in imgData.data) {//添加图片节点
                //console.log(i);
                var ccontent = document.createElement("div");
                ccontent.className = "box";
                cparent.appendChild(ccontent);
                var boximg = document.createElement("div");
                boximg.className = "box_img";
                ccontent.appendChild(boximg);
                var aimg = document.createElement("a");
                aimg.href = "img/" + imgData.data[i].src;
                boximg.appendChild(aimg);
                var img = document.createElement("img");
                img.src = "img/" + imgData.data[i].src;
                aimg.appendChild(img);
            }
            imgLocation("container", "box");
        }
    }
};

function checkFlag() {
    var cparent = document.getElementById("container");
    var ccontent = getChildrenElement(cparent, "box");
    var lastContentHeight = ccontent[ccontent.length - 1].offsetTop;
    var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
    var pageHeight = document.documentElement.clientHeight || document.body.clientHeight;
    //console.log(lastContentHeight + ":" + scrolltop + ":" + pageHeight);
    if (lastContentHeight < scrolltop + pageHeight)
        return true;
}

//将content储存在数组中
function getChildrenElement(parent, content) {
    var contentArr = [];
    var contentAll = parent.getElementsByClassName(content);
    //console.log(contentAll.length);
    for (var i = 0; i < contentAll.length; i++) {//为什么这里不能用var i in contentAll
        contentArr.push(contentAll[i]);
    }
    return contentArr;
}

//将parent下所有的content取出
function imgLocation(parent, content) {
    var cparent = document.getElementById(parent);
    var ccontent = getChildrenElement(cparent, content);
    var imgWidth = ccontent[0].offsetWidth;
    var cols = Math.floor(document.documentElement.clientWidth / imgWidth);
    //console.log(cols);
    cparent.style.cssText = "width:" + imgWidth * cols + "px;margin:0 auto";

    //获取衔接点
    var boxHeightArr = [];
    for (var i in ccontent) {
        if (i < cols) {
            boxHeightArr[i] = ccontent[i].offsetHeight;
            //console.log(boxHeightArr[i]);
        } else {
            var minHeight = Math.min.apply(null, boxHeightArr);
            //console.log(minHeight);
            var minIndex = getMinIndex(boxHeightArr, minHeight);
            ccontent[i].style.position = "absolute";
            ccontent[i].style.top = minHeight + "px";
            ccontent[i].style.left = ccontent[minIndex].offsetLeft + "px";
            boxHeightArr[minIndex] += ccontent[i].offsetHeight;

        }
    }
}

function getMinIndex(boxHeightArr, minHeight) {
    for (var i in boxHeightArr)
        if (boxHeightArr[i] == minHeight)
            return i;
    return -1;
}
</script>
</html>

2.  3D翻页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>3D翻页轮播</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            background: url("img/0.jpg") no-repeat center/100%;
            /*overflow: hidden;*/
        }

        .wrap {
            position: relative;
            width: 1000px;
            height: 612px;
            margin: 100px auto;
            background: url("img/0.jpg") no-repeat 100%;
            perspective: 6000px; /*3d景深*/
            box-shadow: 0 0 18px pink;
        }

        .left, .right {
            position: absolute;
            right: 0;
            top: 0;
            width: 50%;
            height: 100%;

        }

        .left {
            transform: rotateY(0deg);
            transform-origin: left;
            transform-style: preserve-3d; /*3d属性*/
            z-index: 1;
        }

        .on {
            transform: rotateY(-180deg);
            transition: transform 1.5s ease-in-out;
        }

        .right {
            background: url("img/1.jpg") no-repeat right top 50%;
        }

        .prev, .next {
            position: absolute;
            width: 100%;
            height: 100%;
        }

        .prev {
            background: url("img/0.jpg") no-repeat right top 50%;
        }

        .next {
            background: url("img/1.jpg") no-repeat left top 50%;
            transform: translateZ(-1px) scale(-1, 1); /*scale(x,y)负值可以达到镜像,translateZ(-1px)改变层次*/
        }

    </style>
</head>
<body>
<div class="wrap">
    <div class="left">
        <div class="prev"></div>
        <div class="next"></div>
    </div>
    <div class="right"></div>
</div>
</body>
<script>
    /**
     * 防止全局变量污染
     */
    (function () {
            var oLeft = document.querySelector(".left");//获取元素querySelector(".left");
            var oPrevImg = document.querySelector(".prev"),
                oNextImg = document.querySelector(".next"),
                oWrapImg = document.querySelector(".wrap"),
                oRightImg = document.querySelector(".right"),
                oBodyImg = document.querySelector("body");

            var index = 0,//当前第几张图
                isClick = false;//多次点击的开关

            function change() {
                if (isClick) return;
                isClick = true;
                index++;
                index %= 4;
                oLeft.classList.add("on");//添加类名,可维护性
                document.addEventListener("transitionend", function () {//transitionend
                    oLeft.classList.remove("on");
                    oBodyImg.style.backgroundImage =
                        oPrevImg.style.backgroundImage =
                            oWrapImg.style.backgroundImage = "url('img/" + index + ".jpg')";

                    oNextImg.style.backgroundImage =
                        oRightImg.style.backgroundImage = "url('img/" + (index + 1) % 4 + ".jpg')";
                    isClick = false;
                });
            }

            document.onclick = function () {
                change();
            }

        }
    )();
</script>
</html>

3.  网易轮播图

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

        .wrap {
            width: 1200px;
            height: 367px;
            margin: 80px auto;
        }

        .wrap .imgBox ul {
            position: relative;
            width: 1200px;
            height: 336px;
            overflow: hidden;
        }

        .wrap .imgBox ul li {
            position: absolute;
            list-style: none;
            width: 730px;
            height: 336px;
            transition: transform .2s ease;
        }

        .wrap .imgBox ul .list1 {
            z-index: 1;
            transform: scale(0.81);
            transform-origin: 0 100%;
        }

        .wrap .imgBox ul .list2 {
            z-index: 2;
            transform: translateX(235px);
        }

        .wrap .imgBox ul .list3 {
            z-index: 1;
            transform: translateX(730px) scale(0.81);
            transform-origin: 100% 100%;
        }

        .wrap .imgBox ul .list4 {
            transform: translateX(965px) scale(0.81);
            transform-origin: 100% 100%;
        }

        .wrap .imgBox ul .list5 {
            transform: translateX(1200px) scale(0.81);
            transform-origin: 100% 100%;
        }

        .wrap .imgBox ul .list6 {
            transform: translateX(1435px) scale(0.81);
            transform-origin: 100% 100%;
        }

        .wrap .imgBox ul li img {
            width: 730px;
            height: 336px;

        }

        .wrap .lineBar {
            width: 1200px;
            height: 31px;
            text-align: center;
        }

        .wrap .lineBar span {
            display: inline-block;
            width: 35px;
            height: 3px;
            margin-left: 4px;
            background-color: #cccccc;
        }
    </style>
</head>
<body>
<!--
     div.wrap>(div.imgBox>ul>li.list$*6>img[src="img/0$.jpg"])+div.lineBar>span*6
     -->
<div class="wrap">
    <div class="imgBox">
        <ul>
            <li class="list1"><img src="img/01.jpg" alt=""></li>
            <li class="list2"><img src="img/02.jpg" alt=""></li>
            <li class="list3"><img src="img/03.jpg" alt=""></li>
            <li class="list4"><img src="img/04.jpg" alt=""></li>
            <li class="list5"><img src="img/05.jpg" alt=""></li>
            <li class="list6"><img src="img/06.jpg" alt=""></li>
        </ul>
    </div>
    <div class="lineBar"><span></span><span></span><span></span><span></span><span></span><span></span></div>
</div>
</body>
<script>
    (function () {
        var listArray = document.querySelectorAll(".wrap .imgBox ul li"),
            lineBar = document.querySelectorAll(" .wrap .lineBar span"),
            oImgBox = document.querySelector(".wrap .imgBox"),
            oName = [],
            index = 0,
            listLength = listArray.length;
        for (var item of listArray) {
            oName.push(item.className);
        }

        function nextPic() {//把最后一个放到第一个位置
            oName.unshift(oName[5]);
            oName.pop();
            for (var i = 0; i < listLength; i++)
                listArray[i].className = oName[i];
            index++;
            index %=6;
            changeColor();
        }

        function prePic() {//把第一个放到最后一个位置
            oName.push(oName[0]);
            oName.shift();
            for (var i = 0; i < listLength; i++)
                listArray[i].className = oName[i];
            index--;
            if (index<0) index=5;
            changeColor();
        }

        function changeColor() {
            for (var i = 0; i < listLength; i++) {
                if (i == index)
                    lineBar[index].style.backgroundColor = "green";
                else
                    lineBar[i].style.backgroundColor = "#cccccc";
            }
        }
        changeColor();

        var eleSel = ["list1", "list3"];
        var eleAct = ["prePic", "nextPic"];
        oImgBox.addEventListener("click", function (e) {
            var e = e || window.event;
            var ele = e.target.parentNode.getAttribute("class");
            if (ele == "list3") nextPic();
            if (ele == "list1") prePic();
            //window[eleAct[eleSel.indexOf(ele)]]();
        });
    })();
</script>
</html>

4.  京东轮播图

//京东轮播图
(function () {
    var oLefter = document.querySelector(".j-content .content-wrap01 .content02 .lefter");
    var oRighter = document.querySelector(".j-content .content-wrap01 .content02 .righter");
    var oImages = document.querySelectorAll(".j-content .content-wrap01 .content02 .banner-img a");
    var oCircle = document.querySelectorAll(".j-content .content-wrap01 .content02 .circle span");
    var oBanner = document.querySelector(".j-content .content-wrap01 .content02");
    var index = 0;
    var lastIndex = 0;
    var timer = 0;//定时器的返回值是number类型

    //方向点击切换
    oLefter.onclick = function () {
        change(function () {
            index--;
            if (index < 0) index = oImages.length - 1;
        });
    };
    oRighter.onclick = function () {
        rightChange();
    };

    function rightChange() {
        change(function () {
            index++;
            index %= oImages.length;
        });
    }

    //鼠标移动到圆的切换
    for (var i = 0; i < oCircle.length; i++) {
        oCircle[i].index = i;//在每个圆中自定义一个index属性,核心点
        oCircle[i].onmouseover = function (e) {
            change(function () {
                index = e.currentTarget.index;//核心点,想想为什么不能用this.index
            });
        }
    }

    //自动轮播
    function auto() {
        timer = setInterval(function () {
            rightChange();
           // console.log(index);
        }, 3000);
    }
    auto();

    //鼠标进入轮播图清除定时时间
    oBanner.onmouseenter = function () {
        clearInterval(timer);
    };
    //鼠标移出自动轮播
    oBanner.onmouseout = function () {
        clearInterval(timer);//清除重复的定时器,修复bug
        auto();
    };

    //change函数
    function change(callback) {
        //prev
        oImages[lastIndex].classList.remove("banner-on");//className = '';
        oCircle[lastIndex].classList.remove("circle-on");
        //index变化
        callback && callback();//防止报错
        //next
        oImages[index].classList.add("banner-on");//className="banner-on";
        oCircle[index].classList.add("circle-on");
        //lastIndex变化
        lastIndex = index;
    }
})();

5.  京东公告栏和线条跟随

(function () {
    var oLine = document.querySelector(".j-content .content-wrap01 .content04 .item .li-2 .line"),
        oPromotion = document.querySelector(".j-content .content-wrap01 .content04 .item .li-2 .a2-1"),
        oNotice = document.querySelector(".j-content .content-wrap01 .content04 .item .li-2 .a2-2");
    var promote = document.querySelector(".j-content .content-wrap01 .content04 .item .li-2 .promotion"),
        note = document.querySelector(".j-content .content-wrap01 .content04 .item .li-2 .notice");

    //促销栏和下划线的显示
    oPromotion.onmouseenter = function () {
        oLine.classList.remove("line-on");
        oLine.addEventListener("transitionend", function () {
            note.classList.add("text-none");
            promote.classList.remove("text-none");
        });
    };

    //公告栏和下划线的显示
    oNotice.onmouseenter = function () {
        oLine.classList.add("line-on");
        oLine.addEventListener("transitionend", function () {
            promote.classList.add("text-none");
            note.classList.remove("text-none");
        });
    }

})();

6.  京东秒杀

/*京东秒杀*/

(function () {
    var timeData = {//获取时间数据
        oHours: document.querySelector(".j-content .content-wrap02 .flashDeals a ul .flashTimer .hours"),
        oMinimums: document.querySelector(".j-content .content-wrap02 .flashDeals a ul .flashTimer .minimums"),
        oSeconds: document.querySelector(".j-content .content-wrap02 .flashDeals a ul .flashTimer .seconds"),
    };

    //计时器
    function timer(time) {
        if (Number(time.oSeconds.innerHTML) > 0) {
            change(time.oSeconds);
        } else {
            if (Number(time.oMinimums.innerHTML) > 0) {
                change(time.oMinimums);
                time.oSeconds.innerHTML = 59;
            } else {
                if (Number(time.oHours.innerHTML) > 0) {
                    change(time.oHours);
                    time.oMinimums.innerHTML = 59;
                    time.oSeconds.innerHTML = 59
                } else {
                    clearInterval();
                }
            }
        }
    }

    //计时变化
    function change(data) {
        var count = Number(data.innerHTML);
        // console.log(typeof  data.innerHTML);
        count--;
        if (count < 10)
            data.innerHTML = "0" + count;
        else
            data.innerHTML = count;
    }

    //定时
    setInterval(function () {
        timer(timeData);
    }, 1000);

})();

7.  京东搜索框热词推荐

/*热词变化*/
(function () {
    var data01 = ["海尔空调", "烧烤炉", "奶瓶消毒器", "挂烫机", "云南白药牙膏", "U盘16G", "魅族手机", "油烟机"];
    var data02 = ["1元享800M", "家电清凉节", "建材3件8折", "巴味渝珍李"];
    var length01 = data01.length,
        index01 = 0,
        length02 = data02.length,
        index02 = 0,
        timer02 = 0;

    var oPlaceholder = document.querySelector(".search-wrap .search-box .searcher .searchText"),
        oHotWords = document.querySelector(".search-wrap .search-hotWords .a-1");

    var flag = false;

    //placeholder的热词切换
    setInterval(function () {
        if (!flag) {
            index01++;
            index01 %= length01;
            oPlaceholder.setAttribute("placeholder", data01[index01]);
        }
    }, 5000);

    //搜索框获取和失去焦点时,placeholder的热词消失和出现
    oPlaceholder.onfocus = function () {
        flag = true;
        oPlaceholder.setAttribute("placeholder", "");
    };
    oPlaceholder.onblur = function () {
        flag = false;
        oPlaceholder.setAttribute("placeholder", data01[index01]);
    };

    //推荐热词的切换函数
    function auto() {
        timer02 = setInterval(function () {
            index02++;
            index02 %= length02;
            oHotWords.innerHTML = data02[index02];
        }, 3000);
    }

    auto();
    //鼠标移入后,推荐热词停止切换
    oHotWords.onmouseenter = function () {
        clearInterval(timer02);
    };
    //鼠标移出后,推荐热词继续切换
    oHotWords.onmouseout = function () {
        clearInterval(timer02);
        auto();
    };

})();