NPlayer - H5弹幕播放器增加带倒计时的启动和暂停贴片广告

老六

文章最后更新时间:2026年01月04日

NPlayer是一款兼容性超强的H5弹幕播放器,近来被许多视频站点引用,今天来做一个NPlayer增加启动时和暂停时的贴片广告教程,废话不多说直接进入主题:

1,引入NPlayer和JQuery静态文件

script src="/js/NPlayer点min点js"></scriptscript type="text/JavaScript" src="cdn点staticfile点org/JQuery/3.4.1/jquery.min点js"></script


2,初始化NPlayer

const player = new NPlayer.Player({src: 'https://xmsdn.com/static/demo.M3U8',    poster: 'https://xmsdn.com/static/demo.jpg',});player.mount('#player');


3,在页面追加一个放置贴片广告的容器

//贴片图片urlvar adpic="https://xmsdn.com/static/ad.jpg";//贴片跳转链接var adlink='https://www.llbk.cn';//倒计时读秒var adtim='9';//是否自动关闭,是=1,否=0,var autoclose='1';//追加贴片元素$('#player').prepend('<div class="adbox"><a href="' + adlink + '" target="_blank" rel="nofollow"><img src="' + adpic + '"></a><span id="closead">关闭广告</span><span id="adtext">秒后可关闭广告</span><span id="adtime">'+adtim+'</span></div><style type="text/CSS">.adbox{position:absolute;z-index:99999999999;margin:auto;top:0;bottom:0;left:0;right:0;width:500px;height:320px}.adbox img{width:100%;height:100%;position:absolute;margin:auto;top:0;left:0;border-radius:7px}#adtime,#adtext,#closead{position:relative;z-index: 99999999999;color:#FFF;background:#181818;float:right;font-size:14px}#adtime{padding: 10px 1px 10px 10px;border-radius: 5px 0 0 5px;color:#FF9900}#adtext{padding: 10px 10px 10px 1px;border-radius: 0 5px 5px 0;}#closead{display:none;padding:10px;border-radius:5px;cursor: pointer;}@media (max-width: 768px){.adbox{width:65%;height:65%;}#adtime{padding: 5px 0 5px 5px;border-radius: 5px 0 0 5px}#adtext{padding: 5px 5px 5px 0;border-radius: 0 5px 5px 0;}#closead{padding:5px;border-radius:5px;}}</style>');


4,监听NPlayer播放器状态,在启动时和暂停时将贴片广告显示

player.on('LoadedMetadata',function(){function tipstime(count){$('#adtime').text(count);if (count == 0) {$("#adtext,#adtime,#closead").toggle();if (autoclose == 1) {$(".adbox").toggle()}player.on('Pause', function() {    			$(".adbox").show();$("#closead").show();});player.on('Play',function() {$(".adbox").hide();$("#closead").hide();});} else {count -= 1;setTimeout(function () {tipstime(count);}, 1000);}}tipstime(adtim);});


5,把贴片广告上的关闭按钮绑定一个点击事件

$('#player').on("click",'#closead',function(e){$(".adbox").toggle();});


文章版权声明:除非注明,否则均为tools工具箱原创文章,转载或复制请以超链接形式并注明出处。

取消
微信二维码
微信二维码
支付宝二维码