如何在markjs插件返回首个匹配项时触发JavaScript提示框?
实现mark.js跳转至首个匹配项时触发提示框的方案
要实现跳转回首个匹配项时弹出提示框,我们只需要在切换匹配项的逻辑里增加判断:当从其他匹配项切换到第一个的时候,触发JavaScript提示。具体修改步骤如下:
1. 跟踪切换前的索引
在处理「上一个/下一个」按钮点击事件时,先保存当前的索引值,用来判断是否是从其他位置跳回首个匹配项。
2. 增加跳转回首个的判断逻辑
当修改后的索引变为0,且之前的索引不是0时,就弹出提示框。
下面是修改后的完整JS代码:
$(function() { // the input field var $input = $("input[type='search']"), // clear button $clearBtn = $("button[data-search='clear']"), // prev button $prevBtn = $("button[data-search='prev']"), // next button $nextBtn = $("button[data-search='next']"), // the context where to search $content = $(".content"), // jQuery object to save <mark> elements $results, // the class that will be appended to the current // focused element currentClass = "current", // top offset for the jump (the search bar) offsetTop = 50, // the current index of the focused element currentIndex = 0; /** * Jumps to the element matching the currentIndex */ function jumpTo() { if ($results.length) { var position, $current = $results.eq(currentIndex); $results.removeClass(currentClass); if ($current.length) { $current.addClass(currentClass); position = $current.offset().top - offsetTop; window.scrollTo(0, position); } } } /** * Searches for the entered keyword in the * specified context on input */ $input.on("input", function() { var searchVal = this.value; $content.unmark({ done: function() { $content.mark(searchVal, { separateWordSearch: true, done: function() { $results = $content.find("mark"); currentIndex = 0; jumpTo(); } }); } }); }); /** * Clears the search */ $clearBtn.on("click", function() { $content.unmark(); $input.val("").focus(); }); /** * Next and previous search jump to */ $nextBtn.add($prevBtn).on("click", function() { if ($results.length) { // 保存切换前的索引,用于判断是否跳回首个 const oldIndex = currentIndex; currentIndex += $(this).is($prevBtn) ? -1 : 1; if (currentIndex < 0) { currentIndex = $results.length - 1; } if (currentIndex > $results.length - 1) { currentIndex = 0; } // 当从其他匹配项跳回首个时,触发提示 if (currentIndex === 0 && oldIndex !== 0) { alert('已回到首个匹配项!'); } jumpTo(); } }); });
逻辑说明
- 我们通过
oldIndex记录切换前的匹配项索引,只有当切换后索引变为0,且之前不是0时,才会触发提示——这样就排除了首次搜索定位到首个匹配项的情况,只对「跳转回」的动作生效。 - 提示框内容可以根据你的需求修改,比如换成自定义模态框,只要替换
alert()里的内容即可。
内容的提问来源于stack exchange,提问作者nico
相关产品推荐
相关产品推荐

