JQ实现弹幕

来源:互联网 发布:ug8.0车削加工编程 编辑:程序博客网 时间:2024/05/01 23:05
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            #box{
                width: 1300px;
                height: 600px;
                border: 1px solid black;
                background: skyblue;
                margin: 50px auto;
                position: relative;
                overflow: hidden;
            }
            #txt{
                width: 400px;
                height: 50px;
                margin-left: 25%;
                
            }
            #btn{
                width: 100px;
                height: 50px;
                border: 1px solid black;
                position: absolute;
                background: gray;
                text-align: center;
                line-height: 50px;
                text-decoration: none;
                font-size: 20px;
            }
            span{
                position: absolute;
            }
        </style>
        <script src="jxj/js/jquery-1.9.1.min.js"></script>
        <script>
            $(function(){
                $("#btn").click(function(){
                    //定义一个变量存储输入的字符串
                    $str = $("#txt").val();
                    //定义一个变量用来存储top值。最小值是0,最大值是600.
                    $top = Math.random() * 560;
                    //定义词一个变量存储字体的大小,最小值10,最大值40.
                    $fon = Math.random() * 30 + 10;
                    //设置span的颜色
                    $arr = ["red","blue","yellow","black","green","pink","orange","purple","white","sienna"];
                    $num = Math.floor(Math.random() * 10);
                    $col = $arr[$num];
                    //为span设置随机的速度,最快速度为2000.
                    $speed = Math.random() * 10000 + 2000;
                    //创建span节点追加到div中
                    $("<span></span>").appendTo("#box").text($str).addClass("span").siblings().removeClass("span");
                    $(".span").css({"font-size":$fon});
                    //获取span的宽度
                    $wid = $(".span").width();
                    //设置样式
                    $(".span").css({"top":$top,"color":$col,"right":-$wid});
                    //设置目的地、速度、运动方式、回调函数。
                    $(".span").animate({"left":-$wid},$speed,"linear",function(){
                        $(this).remove();
                    });
                })
            })
        </script>
    </head>
    <body>
        <div id="box"></div>
        <input type="text" id="txt"/>
        <a href="javascript:;" id="btn">发表评论</a>
    </body>
</html>