<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; outline: none; border: 0; }
.bigbox { width: 600px; height: 450px; background: plum; margin: 50px auto; }
.imgbox { width: 600px; height: 400px; position: relative; }
.imgbox>img { width: 100%; height: 100%; }
.say { width: 100%; height: 50px; display: flex; justify-content: space-between; }
.inp { width: 80%; background: lightgray; }
.btn { width: 20%; background: gainsboro; }
.imgbox>p { position: absolute; left: 600px; display: flex; white-space: nowrap; }
.imgbox>p img { width: 20px; height: 20px; border-radius: 50%; } </style> </head>
<body> <div class="bigbox"> <div class="imgbox"> <img src="../img/pic2.jpg" alt=""> <!-- <p> <img src="../img/index_04.jpg" alt=""> <span>弹幕666</span> </p> --> </div> <div class="say"> <input type="text" class="inp" placeholder="请输入弹幕"> <button class="btn">发送</button> </div> </div> <script> var oBigbox = document.querySelector('.bigbox') var oImgbox = oBigbox.querySelector('.imgbox') var oSay = oBigbox.querySelector('.say') var oinp = oSay.querySelector('.inp') var oBtn = oSay.querySelector('.btn')
oBtn.onclick = function (e) { var e = e || event var msg = oinp.value if (msg) createMsg(msg) } //生成随机数 function rand(min, max) { return parseInt(Math.random() * (max - min) + min) }
//创建弹幕 function createMsg(msg) { var oP = document.createElement('p') oP.innerHTML = ` <img src="../img/index_04.jpg" alt=""> <span>${msg}</span> ` oImgbox.appendChild(oP) var maxX = oImgbox.clientWidth - oP.offsetWidth var maxY = oImgbox.clientHeight - oP.offsetHeight var y = rand(0, maxY) oP.style.top = y + 'px' // timeDown() move(10, -oP.offsetWidth, oP, 'left', function () { oP.remove() }) } //发表弹幕倒计时 function timeDown() { oBtn.innerHTML = '5S后再次发送' oBtn.disabled = true var count = 5 clearInterval(t) t = setInterval(function () { count-- oBtn.innerHTML = count + 'S后再次发送' if (count <= 0) { clearInterval(t) oBtn.innerHTML = '发送' oBtn.disabled = false } }, 1000) } //弹幕匀速运动 function move(speed, end, ele, attr, cb) { var cur = parseInt(getStyle(ele, attr)) var speed = end > cur ? speed : -speed var t1 = setInterval(function () { cur += speed ele.style[attr] = cur + 'px' if (Math.abs(cur - end) < Math.abs(speed)) { cur = end ele.style[attr] = cur + 'px' clearInterval(t1) //运动结束之后删除弹幕 cb && cb() } }, 50) } //获取元素的css样式 function getStyle(ele, attr) { if (window.getComputedStyle) { return getComputedStyle(ele)[attr] } return ele.currentStyle[attr] } </script> </body>
</html>