JQuery简单实现弹幕滑动效果

Posted on Dec 5, 2017

某需求需要这么玩

于是写了个,备份用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!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,
                 ))).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