MENU

静态博客插入音乐

March 7, 2020 • 开发

最近突发奇想🤔,有没有给每个文章单独插入一首音乐办法,既不改变Gridea的文件,又增加一个新的选项,几经思考后发现可以从文章内容入手😃,先坐下来听听音乐,等我慢慢道来

插曲

我本来时候打算用正则表达式匹配<%= post.content %>来获取设置的音乐ID,但是在这疯狂报错,无奈之下用了DOM来获取😓

var content = '<%= post.content %>'

如果有大佬知道报错原因麻烦告诉我一下

实现过程

为了图方便我就直接引用了网易云音乐的iframe外链,只要提供音乐ID,并且不受版权限制就能直接播放,理论上其他方式的外链或者自己实现也可以使用这个方法

<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=XXXXX&auto=1&height=66"></iframe>

post.content前面添加一个div用于放播放器

<div id="musicBox"></div>

灵性的让它居中一下满足强迫症

#musicBox{
    width: 100%;
    text-align: center;
}

post.content下方添加一段脚本用于动态添加播放器

var music = document.getElementById('music')
if(music != null){//存在
    var id = music.innerHTML;
    var code = '<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=440 height=86 src="//music.163.com/outchain/player?type=2&id='+id +'&auto=1&height=66"></iframe>'
    console.log('id:' +id);
    var frame = document.createElement("frame")
    frame.src='//music.163.com/outchain/player?type=2&id='+id;
    frame.frameBorder=0;
    frame.marginHeight=0;
    frame.marginWidth=0;
    frame.clientWidth=440;
    frame.clientHeight=86;          
    frame.id='Music'
    var box = document.getElementById('musicBox');
    musicBox.innerHTML = code;
}

细心的人就会问了,这个var id = music.innerHTML;从何而来?

诶~最后无中生有这一下才是最妙的😆
code.png
总所周知,.md文章内容最后会以HTML的网页格式展现出来,我们不妨在写文章的时候添加

<p id='music'>音乐ID</p>

这不就来了嘛,最后把这一段隐藏一下

#music{display: none;}

大功告成!🔨

效果

只需要在写文章的时候添加对应的music代码,就能对每一篇文章设置独立的音乐,岂不美哉
~OGXCS_M_BCY__G__V5N9_D.png

Last Modified: March 18, 2020
Leave a Comment

6 Comments
  1. 可以用正则匹配163的网址来处理 https://immmmm.com/post-show-douban-item/

    1. @林木木我想着用正则匹配来着,可是那个地方当时怎么都改报错@(泪),可能是我太菜了@(心碎)

  2. orange orange

    谢谢,非常有用!

    1. orange orange

      @orange但是我不知道 #music 那段应该放哪,求大佬指点一下,谢谢

    2. @orangecss 放在样式文件末尾就行了,一般是主题目录下style/customStyle.less

    3. orange orange

      @SoSilentok,谢谢@(大拇指)