最近需要項目需要實現彈幕,網上參考了各種方法,最后覺得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區域有沒有彈幕
新聞熱點
疑難解答