<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>js实现弹幕效果</title> <style> #play { width: 600px; height: 500px; background-color: #000; } /*方便js获取高度*/ #danmu{ width:600px; height:500px; background-color:#fff; z-index:9999; background-color: rgba(0, 1, 0, 0.1); } #textStyle { position: absolute; font-size: 24px; color: #ffffff; } </style> </head> <body> <div id="play"> <div id="danmu"></div> </div> <input type="text" id="text" value="这是弹幕..."/> <input type="button" value="发送" onclick="danmu()"/> <script src="jquery-3.1.0.min.js"></script> <script> var si; // 初始化定义定时器变量 function danmu() { // 每次执行弹幕函数的前清除一次定时器 clearInterval(si); var text = $(‘#text‘); var danmu = $(‘#danmu‘); var textStyle = ‘<span id="textStyle">‘ + text.val() + ‘</span>‘; danmu.get(0).innerHTML = textStyle; var textTop = Math.round(Math.random()*danmu.height()) + ‘px‘; var textLeft = danmu.width() + ‘px‘; var textStyleObj = $(‘#textStyle‘); textStyleObj.css({ ‘left‘: textLeft, ‘top‘: textTop }); var x = parseInt(textStyleObj.css(‘left‘)); //console.log(x); //textMove(x); var animateLeft = 600; si = setInterval(function () { if(animateLeft < -parseInt(textStyleObj.width())) { // 停止定时器,清空弹幕 clearInterval(si); danmu.text(‘‘); //console.log(‘清除定时器‘); }else { // 弹幕的left值减一 animateLeft--; //console.log(animateLeft); } textStyleObj.css(‘left‘, animateLeft + ‘px‘); }, 10); } </script> </body> </html>
时间: 2024-11-13 07:20:26