JQuery简单实现弹幕滑动效果

某需求需要这么玩

于是写了个,备份用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            margin: 0px;
            padding: 0px;
        }
        .container {
            position: relative;
            background-color:pink;
            height:500px;
            width:100%;
            overflow: hidden;
        }
        .danmaku {
            display: inline-block;
            position: absolute;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="container">

    </div>
    <div id="adddanmaku">click me!</div>
    <script>
    $(document).ready(function(){

        $("#adddanmaku").click(function(){
            addDanmaku("danmakutest!");
        });
    });
    
    function addDanmaku(str)
    {
        $(".container").append("<div class=\"danmaku\">" + str + "</div>");
        var _dm = $(".container").children(".danmaku").last();
        var _width = _dm.width();
        var container_height = $(".container").height();
        var randtop = Math.floor(Math.random()*3*100);//5根据container高度进行自行调整
        var _top = randtop>container_height?"0":randtop;
        _dm.css({"right": -(_width),
                 "top": _top,
                 "color": "#"+(~~(Math.random()*(1<<24))).toString(16)//随机颜色
        });
        _dm.animate({left:-(_width)}, 16000, "linear", function(){$(this).remove();});//弹幕滑行时间可自行调整or随机

    }

    </script>
</body>
</html>

以上,代码在线:https://codepen.io/anon/pen/gXEEaB

那个随机颜色是某天看到知乎的一篇回答顺手记下的。

地址是: https://www.zhihu.com/question/48187821/answer/110002647

发表评论

电子邮件地址不会被公开。 必填项已用*标注