站主个人比较喜欢简约的Typecho主题,但是Typecho的份额较小,其可选的主题数量相对来说非常少。目前站点使用的主体是Anatole 主题,非常简约直观,但是缺少搜索功能,为了解决这个问题,可以通过对主题文件进行简单修改来增加搜索功能。
我们知道,typecho在进行搜索时,页面的路径是“https://站点/index.php/search/搜索的内容”,那么如果我们增加一个搜索框,点击搜索后自动转到该地址就可以实现搜索功能。
这里我们以anatole主题为例,首先是html代码部分,增加一个搜索框的html代码,放置在header.php文件中,紧跟在body标签之后,以实现搜索框出现时,位于整个页面正中间
<!-- 弹出搜索框 -->
<div id="searchModal" class="search-modal">
<form id="searchForm" class="search-form">
<input type="text" id="searchInput" placeholder="请输入搜索内容...">
<button type="submit">搜索</button>
</form>
</div>
随后是该搜索框对应的CSS样式,直接增加到style.css文件中即可,或者可以直接在header.php文件的head标签内增加一个style的标签,放置在标签内,这里我是直接放在了header.php文件中
/* 弹出搜索框的基本样式 */
.search-modal {
display: none; /* 初始化时隐藏 */
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
padding: 20px;
width: 400px; /* 设置固定宽度 */
max-width: 80%; /* 确保在小屏幕上也能良好显示 */
border-radius: 10px; /* 圆角矩形 */
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
}
/* 当搜索框显示时 */
.search-modal.active {
display: block;
}
/* 搜索表单样式 */
.search-form {
display: flex;
flex-direction: column;
}
.search-form input,
.search-form button {
margin: 5px 0;
}
最后,直接在header.php的head标签中,加入对应的javascript代码,如下
document.addEventListener('DOMContentLoaded', function() {
var searchModal = document.getElementById('searchModal');
var searchForm = document.getElementById('searchForm');
var searchInput = document.getElementById('searchInput');
// 使用事件委托处理点击事件
document.body.addEventListener('click', function(event) {
// 检查是否点击了搜索按钮
if (event.target.matches('.search-form-input')) {
searchModal.classList.add('active');
}
// 检查是否点击了非搜索框区域
else if (!searchModal.contains(event.target)) {
searchModal.classList.remove('active');
}
});
// 处理搜索表单提交
searchForm.addEventListener('submit', function(event) {
event.preventDefault();
var query = searchInput.value.trim();
if (query) {
window.location.href = 'https://blog.wslll.cn/index.php/search/' + encodeURIComponent(query);
}
});
});
上述代码增加后,可以保证搜索框在需要的时候被唤醒,同时保证不使用时可以消失。但是问题是,怎样唤起搜索框。那么在上面的代码中可以看到,javascript部分判断了搜索框点击的操作,即如果class为.search-form-input的元素被点击,则唤起搜索框。那么最后,只需要在任意的需要被当做唤起搜索框的元素的标签中增加class=".search-form-input" 即可。
这里站主在首页增加了一个button,并使用fa fa-search图标作为button的图标,随后为button添加了class=".search-form-input"的参数,作为唤起搜索框的按钮。
至此,就成功为无搜索功能的简约主题添加了一个搜索按键。