简介
我正在从任何浏览器实现类似于Ctrl + F的搜索引擎,基本上当我点击下一步按钮时,浏览器必须滚动到名为highlight的类的下一个元素。
我已经有了这种方法。
function scrollToElement(selector, time, verticalOffset) {
time = typeof (time) != 'undefined' ? time : 500;
verticalOffset = typeof (verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({
scrollTop: offsetTop
}, time);
}
这个:
var highlights = $('.highlight');
返回以下数组
我需要找到一种方法来滚动到数组中所需的span,在每个span元素中都有这样的东西。
accessKey: ""
attributes: NamedNodeMap
baseURI: "http://localhost:51939/FBDefault.aspx"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList[1]
className: "highlight"
clientHeight: 0
clientLeft: 0
clientTop: 0
clientWidth: 0
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "al"
innerText: "al"
isContentEditable: false
lang: ""
lastChild: text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: span.caret
nextSibling: text
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 19
offsetLeft: 43
offsetParent: a.dropdown-toggle
offsetTop: 15
offsetWidth: 13
outerHTML: "<span class="highlight">al</span>"
outerText: "al"
ownerDocument: document
parentElement: a.dropdown-toggle
parentNode: a.dropdown-toggle
prefix: null
previousElementSibling: i.fa.fa-calculator.margen
previousSibling: text
scrollHeight: 0
scrollLeft: 0
scrollTop: 0
scrollWidth: 0
shadowRoot: null
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "al"
title: ""
translate: true
webkitdropzone: ""
__proto__: HTMLSpanElement
答案 0 :(得分:1)
要从jQuery搜索中获取第n个元素,您可以使用.get()
,因此您应该能够使用
var span = $(".highlight").get(spanIndex);
scrollToElement(span, time, verticalOffset);
您可以使用某个变量跟踪选择中的当前span
。
答案 1 :(得分:0)
类似的东西:
function scrollToElement($element, time, verticalOffset) {
time = time || 500;
verticalOffset = verticalOffset || 0;
offset = $element.offset();
offsetTop = offset.top + verticalOffset;
$("html, body").animate({
scrollTop: offsetTop
}, time);
};
var Search = function(selector){
this.collection = $(selector);
this.position = 0;
this.next = function(){
if(this.collection.length){
if(this.collection.eq(this.position).length){
scrollToElement (this.collection.eq(this.position));
this.position += 1;
}else if(this.position !== 0){
this.position = 0;
scrollToElement (this.position);
}
}else{
alert('Nothing found!');
}
};
}
var mySearch = new Search('.highlight');
$(button).on('click', mySearch.next());