修改hexo的搜索框

看到有人推荐swiftype,就试着弄到博客里,然后惊喜的发现NexT已经内置了!为了保持整体风格的简洁,我把landscape-plus里的搜索框部分移植了过来。以下是需要修改的地方,总的来说还是蛮容易的。

在菜单栏添加搜索部件

修改<!--增加swiftype搜索功能--><!--增加swiftype搜索功能end-->之间的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<li class="menu-item">
<a id="search-btn">
<i class="menu-item-icon icon-search"></i> <br />
搜索
</a>
<div id="search-form-wrap">
<form class="search-form">
<input type="search" id = "search-form-input" class="st-default-search-input" placeholder="key word" />
</form>
</div>
</li>
{% set swiftype_key = config.swiftype_key %}
<script type="text/javascript">
(function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
(w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
})(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

_st('install','{{swiftype_key}}');
</script>

注意,我这个版本(Apr 16, 2015)里原来的js代码已经过时。

修改css定义

header.styl添加下面代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#search-btn {cursor: pointer;}

#search-form-wrap {
position: absolute;
width: 176px;
height: 30px;
right: -150px;
opacity: 0;
transition: 0.2s ease-out;
&.on {
opacity: 1;
right: 0;
}
+mobile() {
width: 500%;
right: -100%;
}
}
.search-form {
position: absolute;
top: 0;
left: 0;
right: 0;
background: #fff;
padding: 2px 15px;
border-radius: 15px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
#search-form-input {
height:20px;
border: none;
color:#555555;
background: none;
width: 100%;
padding: 0;
outline: none;
line-height: 1;
}

另外,在header.stylheader-inner样式里增加:

1
overflow: hidden;

_mist.styl里删掉site-meta的:

1
margin-left: -20px;

避免撑破页面。

增加弹出动作的js代码

_layout.swig里适当位置添加:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<script type="text/javascript">
var $searchWrap = $('#search-form-wrap'),
isSearchAnim = false,
searchAnimDuration = 200;

var startSearchAnim = function(){
isSearchAnim = true;
};

var stopSearchAnim = function(callback){
setTimeout(function(){
isSearchAnim = false;
callback && callback();
}, searchAnimDuration);
};

$('#search-btn').on('click', function(){
if (isSearchAnim) return;

startSearchAnim();
$searchWrap.addClass('on');
stopSearchAnim(function(){
$('#search-form-input').focus();
});
});

$('#search-form-input').on('blur', function(){
startSearchAnim();
$searchWrap.removeClass('on');
stopSearchAnim();
});
</script>

做完这些别忘了去_config.yml填上swiftype_key,注意是根目录下的配置文件,不是主题里的。