Pau*_*eno 7 javascript usability jquery
好吧......我放弃了!已经失去了3个小时,但无法找到解决此问题的方法:
我需要能够遍历页面上给定文本的下一个出现.就像几乎每个软件上最常见的"查找"功能一样(F3 - 找到下一个).
我正在尝试使用jQuery,但无法通过任何方式使其工作.尝试:NextAll(),next(),最近()(似乎有bug),find(),eq(),children()等等,等等
Bellow是一个可以工作的示例,但是它会转到页面的最后一个元素,而不是循环遍历.
function scrollMe(tow){
var targetOffset = $("*:contains('"+tow+"'):last").offset().top;
$('html,body').animate({scrollTop: targetOffset}, 1000);
}
Run Code Online (Sandbox Code Playgroud)
为了清楚起见我的页面有一组内部有文本的行(div).每次用户单击此行时,必须轻轻地向下(或向上)滚动到下一行,并显示文本(如果有).
样品:
<div onclick="scrollMe('hello');">hello</div>
<div onclick="scrollMe('world');">world</div>
<div onclick="scrollMe('foo');">foo</div>
<div onclick="scrollMe('hello');">hello</div>
<div onclick="scrollMe('bar');">bar</div>
Run Code Online (Sandbox Code Playgroud)
实际上它应该被jQuery包围,但它只是为了说明.
由于您将使用变量作为 contains 的输入,因此我建议跳过选择器。它速度很快,但是您将很难保持变量输入的清洁。
例如,这将突出显示所有出现“two”的文本(小提琴示例):
jQuery(function($) {
var findText = 'two';
$('*').filter(function() {
return $(this).children().length < 1 && $(this).text().indexOf(findText) >= 0;
}).addClass('hilite');
});
Run Code Online (Sandbox Code Playgroud)
为了使其与某种查找下一个功能一起工作,您需要一个变量来跟踪当前索引,以及某种触发器:
jQuery(function($) {
// stores the currently highlighted occurence
var index = 0;
var findText = 'sed';
// you could do this inside the click as well, here, it's cached/faster
// inside click, it would be more dynamic and prevent memory leaks
// just depends on your needs
// you would also want to start with a parent element as $('*') is costly!
var $occurrences = $('*').filter(function() {
return $(this).children().length < 1 && $(this).text().indexOf(findText) >= 0;
});
// remove existing highlights, then find the next occurrence and highlight it
$('#trigger').click(function() {
if( index == $occurrences.length-1 ) { index = 0; }
$occurrences.find('span.hilite').replaceWith(findText);
var $next = $occurrences.eq(++index);
$next.html( $next.html().replace(findText, '<span class="hilite">'+findText+'</span>') );
$(document).scrollTop($next.offset().top-35);
return false;
});
// scroll our trigger link when the screen moves so we can click it again
$(window).scroll(function() {
var top = $(window).scrollTop();
$('#trigger').offset( {top: top, left: 0} );
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |