首页 > 开发 > CSS > 正文

CSS3 实现弹幕的示例代码

2024-07-11 08:36:29
字体:
来源:转载
供稿:网友

最近需要项目需要实现弹幕,网上参考了各种方法,最后觉得transform+transition实现的效果在移动设备上性能最好,在iphone6和红米4上测试,看不到卡顿的感觉。用jquery的animate动画在移动设备上有明显的卡顿。

1.首先创建弹幕区域


<div class="barrage">
<div class="mask">
<!--//弹幕内容-->
</div>
</div>

<input type="text" ng-model="data.comment"/>
<button ng-click="addDanmu()">说两句</button >

2.css


.webPage .barrage{width:100%;height:22%;position: absolute; bottom: 50px; background-color: transparent;pointer-events: none;}
.webPage .barrage .mask{width:100%;height:100%;background:transparent;z-index:100;}

注:以上html,css根据自己需求来即可

3.js


$scope.data = {comment:''};
$scope.danmuCount = 5; //最大弹幕行数
$scope.danmus = ['1545466666还是','9777777','哈哈哈哈哈','对企业读完后环球网好齐齐哈','42115我我我5','556噢噢噢噢45','54哦','54545646','666但近段时间66','56565','454465465565', '1545466666还是','9777777','哈哈哈哈哈','对企业读完后环球网好齐齐哈','42115我我我5','556噢噢噢噢45','54哦','54545646','666但近段时间66','56565','454465465565']; //弹幕数据源

//创建弹幕区域
$scope.createDanmuContent = function () {
var height = 1 / $scope.danmuCount * 100 + '%';
for (var i = 0; i < $scope.danmuCount; i++) {
var item = '<div style="width: 100%; height: '+height+'"></div>';
$('.mask').append(item);
}
$scope.createDanmu ();
};

//开始弹幕绘制
$scope.createDanmu = function () {
var maxCount = 0;
if ($scope.danmus.length > $scope.danmuCount) {
maxCount = $scope.danmuCount;
} else {
maxCount = $scope.danmus.length;
}
var _left = window.screen.width;
for (var i = 0; i < maxCount; i++) {
var _lable = $("<p style='margin: 0;position: absolute;opacity:1;display:table;left: "+_left + 'px'+';color:'+$scope.getRandomColor()+"'>"+$scope.danmus[i]+"</p>");
$(".mask div").each(function () {
//检测该区域是否绘制了弹幕
if ($scope.checkDanmu($(this))) {
$(this).append(_lable);
$scope.moveArray(i);
i--;
return false;
}
});
}
$scope.init_barrage();
};

//将数组第一位放到最后一位,(因弹幕池内容太少,所以没删除已显示的弹幕)
$scope.moveArray = function (i) {
var temp = $scope.danmus[i];
$scope.danmus.splice(i,1);
$scope.danmus.push(temp);
}
//判断content区域有没有弹幕

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表