直接上代码,具体内容步骤已在代码里讲解,
请注意:请在第八行将jq的的导入改成自己本地的才可以。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery.js"></script>
<style>
body {background: #bbb;}
div.top {border: 1px solid gray;width: 90%;margin: auto;
height: 400px;background: #fff;overflow: hidden;}
div.bottom {position: fixed;bottom: 0;width: 100%;height: 150px;
text-align: center;-height: 150px;background: #aaa;}
input {width: 400px;height: 35px;}
button {border: none;width: 80px;height: 36px;}
</style>
</head>
<body>
<div class="top"></div>
<div class="bottom">
<input type="text"><button>发送</button>
</div>
<script>
//设置“button”的点击事件,当点击“button”时触发show函数;
$("button").click(function () {show();});
//设置键盘事件,当用户点击“回车键——13”时一样执行“show”函数;
document.onkeydown = function () {
if (event.keyCode == 13) {show();}};
//开始写“show”函数
function show() {
var val = $(':text').val();
//找到我们要输入的弹幕内容,即文本框的“value”值,但要在点击事件执行后再获取,否者一值为空。
var p = $('<p></p>');
$(p).append(val)//将我们上边获取的文本框的值加到p内
//创造p标签,用于一会插入到屏幕中
var sz = parseFloat(Math.random() * 400);
//设置一个1到400之间的随机数,用它把弹幕的出现位置变换
$(".top").append(p);//把p标签插入到屏幕中
$(".top p").last()
.css("left", "-100%") //设置插入p标签的left值
.animate({ left: "100%", }, 7000,
//设置其的运行速度为7秒,和运行到“left -100%”位置
function () {$(this).remove();//运行到顶点自动删除
})
.offset({top: sz,//设置弹幕出现的位置,用我们上边设置的随机数。
left: "-100%"//设置弹幕出现的位置为-100%,
})
$(':text').val('');//在运行完毕后在清楚文本框的值,避免干扰下次输入
}
</script>
</body>
</html>