弹幕墙

作者: 小奚有话说 | 来源:发表于2017-07-18 17:03 被阅读351次

这两天在FreeCodeCamp上学习全栈知识,需要做一个弹幕墙,话不多说先来一个截图吧。

弹幕.png
界面很简单,首先来看一下布局。
<div>
    <div class="bomb">
        <div class="bomb_show">
        </div>
    </div>
    <div class="send_bomb">
        <input class="b_txt"type="text" placeholder="想说点什么吗?"/>
        <div class="btn_div">
             <input class="b_send" type="button" value="发射"/>
             <input class="b_del" type="button" value="清屏"/>
        </div>
  </div>
</div>

界面布局很简单,就是一个弹幕的div下面一个输入框加两个按钮
那么来看一下css设计

.bomb {
  width:100%;
  height:380px;
}
.bomb_show {
  height:100%;
  widht:100%;
  margin:10px;
  border:1px solid rgb(255,168,0);
}
.send_bomb {
  margin: 20px;
  text-align: center;
}
.b_txt {
  width: 400px;
  height: 40px;
  border-radius: 3px;
  border: 1px solid gray;
}
.btn_div {
  margin-top:10px
}
.b_send {
  border: 1px soild red;
  color: red;
  padding: 0;
  border-radius: 3px;
  height: 40px;
  line-height: 40px;
  font-size: 15px;
  width:200px;
  background-color:white;
}

.b_del {
  border: 1px soild gray;
  color: gray;
  padding: 0;
  border-radius: 3px;
  height: 40px;
  line-height: 40px;
  font-size: 15px;
  width:200px;
  background-color:white;
}
div.text {
  position:absolute;
  right:20px;
  font-size:15px;
  white-space: nowrap;
}

也是如此的简单,就是各种设置,这里我就不一一赘述了。
剩下的就是js了

$(document).ready(function(){
    var width = $(".bomb_show").width();
    var height = $(".bomb_show").height();
    var getRandomColor = function() {
        return '#'+((Math.random() * 0x1000000 << 0).toString(16))
    };
    var send = function() {
        var content = $(".b_txt").val();
        $(".b_txt").val("");
        var $spannode = $('<div class="text">'+content+'</div>');
        spanheight = (height-20)*Math.random()
        $spannode.css({
            top:spanheight,
            color:getRandomColor()
        });
        $(".bomb_show").append($spannode);
        $spannode.animate({left:"20px"},10000,function(){
            $(this).remove();
        });
    }
    $(".b_txt").keypress(function(event){
         if (event.keyCode == "13") {
             $(".b_send").trigger('click');
         }
    });
    $(".b_send").click(function(){
        send();
    });
    $(".b_del").click(function(){
        $(".bomb_show").empty();
    });
});

有点复杂了是吗?


  1. 首先获取幕布的长和宽,后面需要去随机的设置文字的高度。
  2. getRandomColor获取随机的颜色,而后面的keypress则是判断文本输入框是否输入Enter就相当一点击里一次send,send按钮调用最中央的send的函数发送弹幕,清屏只需要使用empty就可以删除幕布中的子元素。
  3. send函数,首先获取到文本输入框的文字,并清空文本输入框,创建一个弹幕的div,在css中有设置其部分的样式,然后设置div的高度以及颜色。之后将该控件添加到幕布中,进行动画即可。animate这里传入了三个参数,第一个是结束状态,即最终文本会移动到20px的位置,中间的是花费的时间,最后是动画完成后的回调函数,这里直接将该空间删除即可。
    简单的弹幕墙就完成了,你也可以来一发哦!

相关文章

网友评论

    本文标题:弹幕墙

    本文链接:https://www.haomeiwen.com/subject/gkackxtx.html