js弹幕效果

<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>Document</title>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    div {
        width: 300px;
        height: 200px;
        background-color: aquamarine;
    }
</style>
</head> <body>
<div></div>
<input type="text">
<input type="submit">


<script>

    var div = document.querySelector('div')
    var inp = document.querySelectorAll('input')[0]
    var btn = document.querySelectorAll('input')[1]
    div.style.position = 'relative'
    // console.log(div, inp, btn)left
    btn.onclick = function (e) {
        e.preventDefault()
        var span = document.createElement('span')
        var left = div.clientWidth
        // console.log(left)
        div.append(span)
        span.innerHTML = inp.value
        inp.value = ""
        span.style.position = "absolute"


        span.style.left = left + 'px'

        //弹幕上下随机位置
        span.style.top = Math.floor(Math.random() * (div.clientHeight / 3)) + 'px'
        // console.log(span.style.left)


        var timer = setInterval(function () {
            left -= 1
            span.style.left = left + 'px';
            // console.log(span.style.left, left)
            if (left < -span.clientWidth) {
                clearInterval(timer)
            }
        }, 10)
    }

</script>
</body>
posted on 2023-04-21 17:27  hqingxiang  阅读(83)  评论(0)    收藏  举报