淘先锋技术网

首页 1 2 3 4 5 6 7

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #but{
            padding: 3px 10px;
            background-color: lightseagreen;
            color: white;
            border: 0;
            border-radius: 5px;
            margin-bottom: 20px;
            cursor: pointer;
        }
        .border{
            width: 400px;
            height: 40px;
            border: 1px solid black;
            border-radius: 20px;
            overflow: hidden;
        }
        #son{
            width: 0;
            height: 100%;
            text-align: center;
            line-height: 40px;
            background-color: goldenrod;
        }
    </style>
</head>
<body>
<button id="but">开始</button>
<div class="border">
    <div id="son">
        <span>0</span><span>%</span>
    </div>
</div>
<script>
    let son = document.getElementById('son')
    let but = document.getElementById('but')
    let span = document.getElementsByTagName('span')
    let num = 0
    let timer = null
	but.onclick = function () {
    	//设置timer == null 是为了保证按钮只能点击一次
		if (timer == null){
			timer = setInterval(function () {
				num += 10
                //给宽进行递增
				son.style.width = num+'px'
                //给百分比进行递增  使用Math.ceil() 是为了防止百分比有小数
                span[0].innerHTML = Math.ceil(num / 400 * 100)
				if (num == 400){
					clearInterval(timer)
				}
			},500)
		}
    }
</script>
</body>
</html>