jQuery實現簡單彈幕製作
阿新 • • 發佈:2020-12-11
在現在的視訊網站,我們在看視訊的時候經常會有彈幕出現,那麼怎麼通過js實現這一效果呢,下面介紹一種簡單的方法。
首先,搭好結構:
頁面中先放一個視訊,視訊下部放一個input 標籤和button按鈕,程式碼如下:
<div class="box"> <div class="top"> <video src="./static/夢然-少年 .mp4" controls autoplay muted></audio> </div> <div class="foot"> <input type="text" name="" id="text"> <input type="button" value="傳送" id="btn"> </div> </div>
再來寫js
首先,我們需要包裝三個函式,也就是傳送到彈幕的隨機顏色、隨機高度和隨機字型大小;程式碼如下:
<script> //隨機獲取字型顏色函式 function getRandomColor(){ var r = Math.floor(Math.random()*255); var g = Math.floor(Math.random()*255); var b = Math.floor(Math.random()*255); return 'rgb('+r+','+g+','+ b +')' } //隨機獲取高度函式 function getRandomHeight(){ var height = $('.top').height() return Math.random()*height-30 } //隨機獲取字型大小函式 function getRandomFontSize(){ return Math.floor(Math.random()*60) }
現在我們需要獲取使用者輸入的內容在將內容顯示到頁面中,並且移動,一直到頁面外就消除,程式碼如下:
//事件註冊 $('#btn').on('click',function(){ if($('#text').val() ==''){ return } $('<span></span>').text($('#text').val()).css({ 'position':'absolute','width':200,'height':50,'color':getRandomColor(),'fontSize':getRandomFontSize(),'right':-200,'top':getRandomHeight() }).animate({right:1000},10000,'linear',function(){ $(this).remove() }).appendTo($('.top')) $('#text').val('') })
最後將鍵盤迴車鍵也繫結事件,讓使用者輸入內容後按下回車鍵和按傳送按鈕有同樣的效果:
$('#text').keydown(function(event){ if($('#text').val() ==''){ return } if(event.keyCode == 13){ $('#btn').click() } }) </script>
最終效果如下
那麼,現在一個簡單的彈幕就製作完成了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。