自学前端之用jquery库写弹幕效果

效果图

在这里插入图片描述

实现思路

想要实现这种效果,从图上看我们得有三个div盒子,第一个div就是全屏的效果,其中又包括颜色为灰色的div盒子。如果文字、输入框、按钮想要同时居中,也需要把它们放在一个盒子中。

HTML

<div id="boxDom">
    <div id="idDom">
        <div class="smallBox">
            <p class="title">吐槽:</p>
            <input type="text" class="text"/>
            <button id="btn">发射</button>
        </div>
    </div>
</div>

CSS

<style>
        body {
            margin: 0;
            padding: 0;
        }
        #boxDom {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
        }
        #idDom {
            width: 100%;
            height: 100px;
            background-color: #666;
            position: fixed;
            bottom: 0px;
        }
        .smallBox {
            display: inline-block;
            width: 430px;
            height: 40px;
            position: absolute;
            left: 0px;
            right: 0px;
            top: 0px;
            bottom: 0px;
            margin: auto;
        }
        .title {
            display: inline;
            font-size: 20px;
            color: #ffffff;
            text-align: center;
        }
        .text {
            height: 20px;
            border-radius: 5px;
        }
        span {
            position: fixed;
            right: -500px;
        }
    </style>

JS代码

$(function () {
		//设置弹幕文字颜色
        var colors = ["red", "green,", "pink", "orange"];

        $("#btn").click(function () {
			//随机获取颜色数组
            var randomColor = parseInt(Math.random() * colors.length);
            //发送的弹幕出现的位置,也进行随机化
            var randomY = parseInt(Math.random() * 400);
			//发送的弹幕文字使用<span>包括起来
            $("<span></span>")
            		//将文本框中的内容写入到span中
                    .text($(".text").val())
                    //给文字设置颜色
                    .css("color", colors[randomColor])
                    //将文字向左靠近,刚开始肯定是隐藏的,注意如果css中不写span样式的话,不会达到我们想要的效果
                    .css("left", "1400px")
                    //这里就是文字距离顶部的位置,随机的
                    .css("top", randomY)
                    //最后我们在设置文字的动画效果
                    //这里分别是终点,显示的时间长短,速度是匀速,最后回调函数写,文字到达终点的时候就将它删除
                    .animate({left: -500}, 6000, "linear", function () {
                        $(this).remove();
                    })
                    //写了以上效果最后记得把它添加到boxDom中。
                    .appendTo("#boxDom");
			//发送后,清空文本内容。
            $(".text").val("");
        });
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋承佑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值