博客园实现可拖拽目录导航【css+js拿来即用】
博客园中实现可拖拽导航【即插即用】
使用说明:将下面的css+js粘在博客园设置中指定位置即可
CSS:粘贴在 ”博客园 -- 设置 -- ‘页面定制CSS代码’“ 中
/*生成博客目录的CSS*/
#uprightsideBar{
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
text-align:left;
position:fixed;/*将div的位置固定到距离top:50px,right:0px的位置,这样div就会处在最右边的位置,距离顶部50px*/
top:50px;
right:0px;
width: auto;
height: auto;
}
#sideBarTab{
/* float:left; */
width:100px;
border:1px solid #e5e5e5;
border-right:none;
text-align:center;
background:#ffffff;
cursor:pointer;
}
#sideBarContents{
float:left;
overflow:auto;
overflow-x:hidden;!important;
width:300px;
min-height:108px;
max-height:460px;
border:1px solid #e5e5e5;
border-right:none;
background:#ffffff;
}
#sideBarContents dl{
margin:0;
padding:0;
}
#sideBarContents dt{
margin-top:5px;
margin-left:5px;
}
#sideBarContents dd, dt {
cursor: pointer;
}
#sideBarContents dd:hover, dt:hover {
color:#A7995A;
}
#sideBarContents dd{
margin-left:20px;
}
#sideBarContents dd.indent3{
margin-left:40px;
}
#sideBarContents dd.indent4{
margin-left:60px;
}
#sideBarContents dd.indent5{
margin-left:80px;
}
#sideBarContents dd.indent6{
margin-left:100px;
}
JS:粘贴在 ”博客园 -- 设置 -- ‘首页HTML代码’“ 中
<!-- fork github 控件 -->
<a href="https://github.com/lihewei7"
class="github-corner" aria-label="View source on Github">
<svg width="80" height="80" viewBox="0 0 250 250"
style="fill:#000000; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media(max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<!-- fork gitee 控件 -->
<!-- <a href="https://gitee.com/lihewei7">
<img style="position: absolute; top: 0; left: 0; border: 0;"
src="https://images.cnblogs.com/cnblogs_com/yege/2304153/o_230425090244_image.png" width="100px" height="30px"><br
alt="Fork me on Gitee" >
</a> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/device@0.2.7/device.min.js"></script> -->
<script language="javascript" type="text/javascript">
// 生成目录索引列表
// ref: http://www.cnblogs.com/wangqiguo/p/4355032.html
// modified by: zzq
function GenerateContentList()
{
var mainContent = $('#cnblogs_post_body');
var h1_list = $('#cnblogs_post_body h1');//如果你的章节标题不是h2,只需要将这里的h2换掉即可
if(mainContent.length < 1)
return;
if(h1_list.length>0)
{
var content = '<a name="_labelTop"></a>';
content += '<div id="navCategory" style="color:#152e97;">';
content += '<p style="font-size:18px;"><b>目录</b></p>';
content += '<ul>';
for(var i=0; i<h1_list.length; i++)
{
var go_to_top = '<div style="text-align: right;"><a href="#_labelTop" style="color:#f68a33">回到顶部</a><a name="_label' + i + '"></a></div>';
$(h1_list[i]).before(go_to_top);
var h2_list = $(h1_list[i]).nextAll("h2");
var li2_content = '';
for(var j=0; j<h2_list.length; j++)
{
var tmp = $(h2_list[j]).prevAll('h1').first();
if(!tmp.is(h1_list[i]))
break;
var li2_anchor = '<a name="_label' + i + '_' + j + '"></a>';
$(h2_list[j]).before(li2_anchor);
li2_content += '<li><a href="#_label' + i + '_' + j + '">' + $(h2_list[j]).text() + '</a></li>';
}
var li1_content = '';
if(li2_content.length > 0)
li1_content = '<li><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a><ul>' + li2_content + '</ul></li>';
else
li1_content = '<li><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a></li>';
content += li1_content;
}
content += '</ul>';
content += '</div><p> </p>';
content += '<hr style="height:1px;border:none;border-top:1px dashed #0066CC;"/>';
if($('#cnblogs_post_body').length != 0 )
{
$($('#cnblogs_post_body')[0]).prepend(content);
}
}
}
GenerateContentList();
</script>
<script type="text/javascript">
var BlogDirectory = {
/*
获取元素位置,距浏览器左边界的距离(left)和距浏览器上边界的距离(top)
*/
getElementPosition:function (ele) {
var topPosition = 0;
var leftPosition = 0;
while (ele){
topPosition += ele.offsetTop;
leftPosition += ele.offsetLeft;
ele = ele.offsetParent;
}
return {top:topPosition, left:leftPosition};
},
/*
获取滚动条当前位置
*/
getScrollBarPosition:function () {
var scrollBarPosition = document.body.scrollTop || document.documentElement.scrollTop;
return scrollBarPosition;
},
/*
移动滚动条,finalPos 为目的位置,internal 为移动速度
*/
moveScrollBar:function(finalpos, interval) {
//若不支持此方法,则退出
if(!window.scrollTo) {
return false;
}
//窗体滚动时,禁用鼠标滚轮
window.onmousewheel = function(){
return false;
};
//清除计时
if (document.body.movement) {
clearTimeout(document.body.movement);
}
var currentpos =BlogDirectory.getScrollBarPosition();//获取滚动条当前位置
var dist = 0;
if (currentpos == finalpos) {//到达预定位置,则解禁鼠标滚轮,并退出
window.onmousewheel = function(){
return true;
}
return true;
}
if (currentpos < finalpos) {//未到达,则计算下一步所要移动的距离
dist = Math.ceil((finalpos - currentpos)/10);
currentpos += dist;
}
if (currentpos > finalpos) {
dist = Math.ceil((currentpos - finalpos)/10);
currentpos -= dist;
}
var scrTop = BlogDirectory.getScrollBarPosition();//获取滚动条当前位置
window.scrollTo(0, currentpos);//移动窗口
if(BlogDirectory.getScrollBarPosition() == scrTop)//若已到底部,则解禁鼠标滚轮,并退出
{
window.onmousewheel = function(){
return true;
}
return true;
}
//进行下一步移动
var repeat = "BlogDirectory.moveScrollBar(" + finalpos + "," + interval + ")";
document.body.movement = setTimeout(repeat, interval);
},
htmlDecode:function (text){
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
},
/*
创建博客目录,
id表示包含博文正文的 div 容器的 id,
mt 和 st 分别表示主标题和次级标题的标签名称(如 H2、H3,大写或小写都可以!),
interval 表示移动的速度
*/
createBlogDirectory:function (id, mt, st, interval){
//获取博文正文div容器
var elem = document.getElementById(id);
if(!elem) return false;
//获取div中所有元素结点
var nodes = elem.getElementsByTagName("*");
//创建博客目录的div容器
var divSideBar = document.createElement('DIV');
divSideBar.className = 'uprightsideBar';
divSideBar.setAttribute('id', 'uprightsideBar');
var divSideBarTab = document.createElement('DIV');
divSideBarTab.setAttribute('id', 'sideBarTab');
divSideBar.appendChild(divSideBarTab);
var h2 = document.createElement('H2');
divSideBarTab.appendChild(h2);
var txt = document.createTextNode('目录导航');
h2.appendChild(txt);
var divSideBarContents = document.createElement('DIV');
divSideBarContents.style.display = 'none';
divSideBarContents.setAttribute('id', 'sideBarContents');
divSideBar.appendChild(divSideBarContents);
//创建自定义列表
var dlist = document.createElement("dl");
divSideBarContents.appendChild(dlist);
var num = 0;//统计找到的mt和st
mt = mt.toUpperCase();//转化成大写
st = st.toUpperCase();//转化成大写
//遍历所有元素结点
for(var i=0; i<nodes.length; i++)
{
var tits = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];
if(tits.indexOf(nodes[i].nodeName) !== -1)
{ // nodes[i].nodeName == mt|| nodes[i].nodeName == st
//获取标题文本
var nodetext = nodes[i].innerHTML.replace(/<\/?[^>]+>/g,"");//innerHTML里面的内容可能有HTML标签,所以用正则表达式去除HTML的标签
//nodetext = nodetext.replace(/ /ig, "");//替换掉所有的
nodetext = BlogDirectory.htmlDecode(nodetext);
//插入锚
nodes[i].setAttribute("id", "blogTitle" + num);
var item;
switch(nodes[i].nodeName)
{
case 'H1': //若为主标题
item = document.createElement("dt");
break;
case 'H3':
item = document.createElement("dd");
item.setAttribute('class', 'indent3');//通过CSS样式定义距离
break;
case 'H4':
item = document.createElement("dd");
item.setAttribute('class', 'indent4');
break;
case 'H5':
item = document.createElement("dd");
item.setAttribute('class', 'indent5');
break;
case 'H6':
item = document.createElement("dd");
item.setAttribute('class', 'indent6');
break;
default:
item = document.createElement("dd");
break;
}
//创建锚链接
var itemtext = document.createTextNode(nodetext);
item.appendChild(itemtext);
item.setAttribute("name", num);
item.onclick = function(){ //添加鼠标点击触发函数
var pos = BlogDirectory.getElementPosition(document.getElementById("blogTitle" + this.getAttribute("name")));
if(!BlogDirectory.moveScrollBar(pos.top, interval)) return false;
};
//将自定义表项加入自定义列表中
dlist.appendChild(item);
num++;
}
}
divSideBarContents.style.display = 'block';
// //如果没有找到标题,则不生成目录导航栏
// if(num == 0) return false;
// /*鼠标进入时的事件处理*/
// // divSideBarTab.onmouseenter = function(){
// // divSideBarContents.style.display = 'block';
// // }
// /*鼠标离开时的事件处理*/
// // divSideBar.onmouseleave = function() {
// // divSideBarContents.style.display = 'none';
// // }
// /*鼠标点击时的事件处理*/
// divSideBarTab.onclick = function(){
// if(divSideBarContents.style.display == "none")
// divSideBarContents.style.display = 'block';
// else {
// divSideBarContents.style.display = 'none';
// }
// }
/**/
document.body.appendChild(divSideBar);
}
};
window.onload=function(){
function isMobile() {
let userAgentInfo = navigator.userAgent;
let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
let getArr = Agents.filter(i => userAgentInfo.includes(i));
return getArr.length ? true : false;
}
// 使用device.js或其他库来检测设备类型
// var isMobile = device.mobile();
var isMobile = isMobile();
BlogDirectory.createBlogDirectory("cnblogs_post_body","h1","h2",20);
// 获取目录容器元素
var tocContainer = document.getElementById('uprightsideBar');
if (isMobile) {
// 在手机端隐藏目录容器
tocContainer.style.display = 'none';
} else {
// 在PC端显示目录容器
tocContainer.style.display = 'block';
}
/*页面加载完成之后生成博客目录*/
// BlogDirectory.createBlogDirectory("cnblogs_post_body","h1","h2",20);
var drag = document.getElementById('uprightsideBar');
// //点击某物体时,用drag对象即可,move和up是全局区域,
// 也就是整个文档通用,应该使用document对象而不是drag对象(否则,采用drag对象时物体只能往右方或下方移动)
drag.onmousedown = function(event){
var event = event || window.event; //兼容IE浏览器
// 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
var diffX = event.clientX - drag.offsetLeft;
var diffY = event.clientY - drag.offsetTop;
if(typeof drag.setCapture !== 'undefined'){
drag.setCapture();
}
document.onmousemove = function(event){
var event = event || window.event;
var moveX = event.clientX - diffX;
var moveY = event.clientY - diffY;
if(moveX < 0){
moveX = 0
}else if(moveX > window.innerWidth - drag.offsetWidth){
moveX = window.innerWidth - drag.offsetWidth
}
if(moveY < 0){
moveY = 0
}else if(moveY > window.innerHeight - drag.offsetHeight){
moveY = window.innerHeight - drag.offsetHeight
}
drag.style.left = moveX + 'px';
drag.style.top = moveY + 'px'
}
document.onmouseup = function(event){
this.onmousemove = null;
this.onmouseup = null;
//修复低版本ie bug
if(typeof drag.releaseCapture!='undefined'){
drag.releaseCapture();
}
}
}
}
</script>