欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript实现正序和倒序

程序员文章站 2022-03-22 21:44:41
...

JavaScript实现正序和倒序

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style>
body{
	    width: 600px;
        height: 400px;
        margin: 50px auto;
}
    li{
        list-style: none;
        width: 100px;
        height: 50px;
        margin-right: 10px;
        margin-top: 10px;
        text-align: center;
        line-height: 50px;
        background-color: #eee;
        float: left;
    }
</style>
<body>
	
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<button id="btn_x">倒序</button>
</body>

<script>
	var liList = document.querySelectorAll("li");
    var btn_x=document.getElementById("btn_x");
    var x_num = false;
    btn_x.onclick=function() {
        
        if(x_num == false) {

            for(var i = liList.length - 1; i > -1; i--) {
              document.querySelector("ul").appendChild(liList[i]);
            }
            x_num = true;
            this.innerHTML="正序";

        } else if(x_num == true) {

            for(var i = 0; i < liList.length; i++) {
               document.querySelector("ul").appendChild(liList[i]);
            }
            x_num = false;
            this.innerHTML="倒序";
        }
    };
</script>
</html>