安全教育考试题库子页面嵌入博客后,就想着通过前端脚本准确快速地查找和定位,这里有个很好的案例,就是12306的车站订票起售时间查找的页面效果。
所以我要做的功能就是:在搜索框输入题目关键字段后,点击Enter
按钮或按Enter
键,可以迅速将页面滚动定位到第一个匹配的位置,将关键字高亮,并可以继续匹配下去,同时保持搜索框和按钮在页面顶部,方便继续查找。
关键代码
HTML
主要呈现一个搜索区域#searchBox
,包含一个输入框,用来输入要查找的关键字段,以及一个Enter
按钮,然后就是前言、使用说明和题库#content
。
<div id="searchBox"> |
CSS
简单对页面内容进行了CSS设置,其中.highlight
用来设置查找结果高亮显示的样式效果。
p { |
jQuery
首先,实现一个固定搜索框和按钮的效果,当页面往下拉滚动时,输入框和按钮始终保持在页面的顶部。
(function($) { |
然后,调用fixDiv()
$(function() { |
接着,当输入关键字段后,点击Enter
按钮或按Enter
键,调用函数highlight()
$(function() { |
函数highlight()
定义:
function highlight() { |
上述代码中的函数clearSelection()
定义如下:
function clearSelection() { |
还有函数showTips()
:
var tipsDiv = '<div class="tipsClass"></div>'; |
到这里就基本完成了。
jQuery引用报错
编译、部署后,Chrome浏览器调试报错:
(index):7695 Uncaught TypeError: $(...).fixDiv is not a function |
我百思不得其解,因为在这之前我已引入了jQuery。后来在Stack Overflow找到了问题所在:
@sholsinger: Check that you’re not loading jQuery into the page twice. Some plugins or plugin libraries like to include jQuery. So it can overwrite your existing jQuery instance and override the $ and jQuery variables with a new – fresh – instance causing existing plugins to be undefined. Plugins are added to the prototype of jQuery when they are defined. So if you destroy the only instance of that object, then the prototype is reset to its original form. And therefore those plugins are no longer part of that prototype.
简单来说就是在上述代码后又加载了一遍jQuery,我一看,果然是,后一个是Hexo编译时引入的,即
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script> |
只需要将其注释掉即可。