js小练习--模拟满天星

效果展示:实际有很多星星在闪烁 只能截到一颗

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample011 - 模拟星空</title>
    <link rel="stylesheet" type="text/css" href="css/cute.css" />
    <link rel="stylesheet" type="text/css" href="css/index1.css" />
</head>
<body>
    <div id="starry-sky">
        <span id="stars">★</span>
    </div>
</body>
<!-- 当页面加载完成,载入JavaScript文件,为Html元素添加动作 -->
<script src="js/index1.js" type="text/javascript" charset="utf-8"></script>
</html>

css代码:

#starry-sky{
    background: rgb(3, 2, 41);
    width: 100%;
    height: 100%;
    position: fixed;
}
#stars{
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 20px;
    display: block;
    color: #fff;
    position: absolute;
}

js代码:

setInterval(function(){
    //   获取浏览器课件区域宽度
    let bodyWidth=document.documentElement.clientWidth;
    //   获取浏览器课件区域高度
    let bodyHeight=document.documentElement.clientHeight;
    //随机坐标x
    let x_offset=parseInt(Math.random() * bodyWidth - 30);
    //随机坐标y
    let y_offset=parseInt(Math.random() * bodyHeight - 30);
    //设置星星x坐标
    document.getElementById("stars").style.left=x_offset+ "px";
    //y坐标
    document.getElementById("stars").style.top=y_offset+ "px";
},1)

新知识:

    //   获取浏览器课件区域宽度

    let bodyWidth=document.documentElement.clientWidth;

    //   获取浏览器课件区域高度

    let bodyHeight=document.documentElement.clientHeight;

    //随机坐标x

    let x_offset=parseInt(Math.random() * bodyWidth - 30);

    //随机坐标y

    let y_offset=parseInt(Math.random() * bodyHeight - 30);

    //设置星星x坐标

    document.getElementById("stars").style.left=x_offset+ "px";

    //y坐标

    document.getElementById("stars").style.top=y_offset+ "px";

猜你喜欢

转载自blog.csdn.net/qq_63533863/article/details/123673002