用jQuery实现弹幕效果
jQuery弹幕效果
弹幕在日常网络中也比较常见,弹幕的种类也是各式各样的,今天也就简单的做一个普通的弹幕效果。
首选认识一下marquee
marquee
HTML marquee 元素() 用来插入一段滚动的文字。你可以使用它的属性控制当文本到达容器边缘发生的事情。
属性
behavior:设置文本在 marquee 元素内如何滚动。可选值有 scroll,slide 和 alternate。 如果未指定值,默认值为 scroll。
bgcolor:通过颜色名称或十六进制值设置背景颜色。
direction:设置 marquee 内文本滚动的方向。可选值有 left, right, up and down。如果未指定值,默认值为 left。
height:以像素或百分比值设置高度。
hspace:设置水平边距。
loop:设置 marquee 滚动的次数。如果未指定值,默认值为 −1,表示 marquee 将连续滚动.
scrollamount:设置每次滚动时移动的长度(以像素为单位)。默认值为 6。
scrolldelay:设置每次滚动时的时间间隔(以毫秒为单位)。默认值为 85。请注意, 除非指定 truespeed 值,否则将忽略任何小于 60 的值,并改为使用 60。
truespeed:默认情况下,会忽略小于60的scrolldelay值。如果存在truespeed,那些值不会被忽略。
vspace:以像素或百分比值设置垂直边距。
width:以像素或百分比值设置宽度。
代码
先构建出基本样式
<style>
.div {
width: 1500px;
height: 800px;
border: solid 1px red;
margin: auto;
position: relative;
}
.txt {
width: 220px;
margin: auto;
padding: 30px;
}
marquee {
font-size: 25px;
font-weight: bold;
color: rebeccapurple;
position: absolute;
}
</style>
<div class="div">
<marquee behavior="" direction="">下方输入,点击发送</marquee>
</div>
<div class="txt">
<input type="text" class="text"><button class="fs">发送</button>
</div>
引用jQuery,并添加事件
$('.fs').click(function() {
var x = $('.text')[0].value
var n = Math.random() * 760
var cr = Math.floor(Math.random() * 256)
var cg = Math.floor(Math.random() * 256)
var cb = Math.floor(Math.random() * 256)//随机改变弹幕颜色
var fs = Math.floor(Math.random() * 20 + 20)
$('.div').append(' <marquee behavior="scroll" loop="2;">' + x + '</marquee>').find('marquee:last').css({
'color': 'rgb(' + cr + ',' + cg + ',' + cb + ')',
'font-size': fs,
'top': n
})
$('.text')[0].value = ''//发送后清空文本框里的字
})
$('.text').keyup(function(e) {//绑定回车键
if (e.keyCode == 13) {
$('.fs').click()
}
});
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./jquery.js"></script>
<title>弹幕</title>
</head>
<body>
<style>
.div {
width: 1500px;
height: 800px;
border: solid 1px red;
margin: auto;
position: relative;
}
.txt {
width: 220px;
margin: auto;
padding: 30px;
}
marquee {
font-size: 25px;
font-weight: bold;
color: rebeccapurple;
position: absolute;
/* top: 10px; */
}
</style>
<div class="div">
<marquee behavior="" direction="">下方输入,点击发送</marquee>
</div>
<div class="txt">
<input type="text" class="text"><button class="fs">发送</button>
</div>
<script>
$('.fs').click(function() {
var x = $('.text')[0].value
// var n = 20
var n = Math.random() * 760
var cr = Math.floor(Math.random() * 256)
var cg = Math.floor(Math.random() * 256)
var cb = Math.floor(Math.random() * 256)
var fs = Math.floor(Math.random() * 20 + 20)
$('.div').append(' <marquee behavior="scroll" loop="2;">' + x + '</marquee>').find('marquee:last').css({
'color': 'rgb(' + cr + ',' + cg + ',' + cb + ')',
'font-size': fs,
'top': n
})
$('.text')[0].value = ''
})
$('.text').keyup(function(e) {
if (e.keyCode == 13) {
$('.fs').click()
}
});
</script>
</body>
</html>