Home >Web Front-end >JS Tutorial >How to achieve barrage effect in js
The specific steps are as follows:
1. Write HTML code:
Create a barrage display wall and two buttons, namely "Send" " and "Clear screen", and set the placeholder in the text box to "Say something?" to prompt the user to enter barrage information here.
<body> <div class="con"> <div id="screen"> <div class="dm_show"> <!-- <div>text message</div> --> </div> </div> <div class="edit"> <p> <input placeholder="说点什么吧?" class="content" type="text" /> </p> <p> <input type="button" class="send" value="发送" /> <input type="button" class="clear" value="清屏" /> </p> </div> </div> </body>
2. Set the CSS style of each label:
<style> .con { background-color: floralwhite; padding: 40px 80px 80px; } #screen { background-color: #fff; width: 100%; height: 380px; border: 1px solid rgb(229, 229, 229); font-size: 14px; } .content { border: 1px solid rgb(204, 204, 204); border-radius: 3px; width: 320px; height: 35px; font-size: 14px; margin-top: 30px; } .send { border: 1px solid rgb(230, 80, 30); color: rgb(230, 80, 0); border-radius: 3px; text-align: center; padding: 0; height: 35px; line-height: 35px; font-size: 14px; width: 159px; background-color: white; } .clear { border: 1px solid; color: darkgray; border-radius: 3px; text-align: center; padding: 0; height: 35px; line-height: 35px; font-size: 14px; width: 159px; background-color: white; } .edit { margin: 20px; text-align: center; } .text { position: absolute; } *{ margin: 0; padding: 0; } .dm_show{ margin: 30px; } </style>
After the CSS code is completed, some screenshots are as follows:
##3. Write JavaScript Code, add button click event<script type="text/javascript" src="../jquery-easyui-1.3.5/jquery.min.js"></script> <script> $(function() { //设置“发送”按钮点击事件,将弹幕体显示在弹幕墙上 $('.send').click(function() { //获取文本输入框的内容 var val = $('.content').val(); //将文本框的内容赋值给val后,将文本框的内容清除,以便用户下一次输入 $('.content').val(''); //将文本框内容用div包裹起来,便于后续处理 var $content = $('<div class="text">' + val + '</div>'); //获取弹幕墙对象 $screen = $(document.getElementById("screen")); //设置弹幕体出现时的上边距,为任意值 var top = Math.random() * $screen.height()+40; //设置弹幕体的上边距和左边距 $content.css({ top: top + "px", left: 80 }); //将弹幕体添加到弹幕墙中 $('.dm_show').append($content); //弹幕体从左端移动到最右侧,时间为8秒,然后直接删除该元素 $content.animate({ left: $screen.width()+80-$content.width() }, 8000, function() { $(this).remove(); }); }); //设置“清屏”点击事件,清除弹幕墙中的所有内容 $('.clear').click(function() { $('.dm_show').empty(); }); }); </script>The screenshot of the final effect is as follows:
Recommended related tutorials:
js tutorial
The above is the detailed content of How to achieve barrage effect in js. For more information, please follow other related articles on the PHP Chinese website!