JQuery实例 当前页面搜索关键词

本页内容
上一节: JQuery_属性

学完jQuery现在我们可以去动手做一些复杂的应用了。

该实例实现类似浏览器Ctrl-F页面内搜索关键词的效果

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title></title>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js" type="application/javascript"></script>
    <script type="text/javascript" charset="utf-8">
        $(function(){
        $('.sop-start').click(function(){
	$('#search-on-page').show();
});
$('.sop-cancel').click(function(){
		$('#search-on-page').hide();
});
var searchedTextLast = '';
var sopIndex = 0;
var sopCnt = 0;
$('.sop-find').click(function(){
			$('.search-found').each(function(){
				$(this).removeClass('current');
			});

	
	var searchedText = $('.sop-keywords').val();
	if(searchedText != searchedTextLast){
		if(searchedTextLast != ''){
			$('.search-found').each(function(){
				$(this).removeClass('search-found');
			});
		}
		$("p:contains('"+searchedText+"')").each( function( i, element ) {console.log(element)
		  var content = $(element).text();
		  content = content.replaceAll( searchedText, '<span class="search-found">' + searchedText + '</span>' );
		  $(element).html(content).promise().done(function(){
		  	sopIndex = 0;
		  	sopCnt = $('.search-found').length;
		  	$('.sop-info').text('共有'+sopCnt+'匹配项,当前为第'+(sopIndex+1));
		  	searchedTextLast = searchedText;
		  	 $([document.documentElement, document.body]).animate({
		    	scrollTop: $('.search-found').first().offset().top-300
			}, 200);
		});;
			
	});
	}else{

		sopIndex++

		$('.sop-info').text('共有'+sopCnt+'匹配项,当前为第'+(sopIndex));
        $('.search-found').eq(sopIndex).addClass('current');
		if(sopIndex >= sopCnt) sopIndex = sopIndex % sopCnt;
			 $([document.documentElement, document.body]).animate({
		    	scrollTop: $('.search-found').eq(sopIndex).offset().top-300
			}, 200);
	}
	
});
                });
        
    </script>
    <style type="text/css" media="screen">
.search-found{
     text-decoration: underline;
}
.search-found.current{
     background: #fffc89;
}
    </style>
</head>
<body>
    <div id="search-on-page" style="">
        <input name="keywords" placeholder="输入H试试看" type="text" class="sop-keywords">
        <button class="sop-find"> Find </button>
        <button class="sop-cancel"> Cancel </button>
        <div class="sop-info"></div>
    </div>
    <p>
    超文本标记语言(英語:HyperText Markup Language,简称:HTML)是一种用于创建网页的标准标记语言。HTML是一种基础技术,常与CSS、JavaScript一起被众多网站用于设计网页、网页应用程序以及移动应用程序的用户界面[3]。网页浏览器可以读取HTML文件,并将其渲染成可视化网页。HTML描述了一个网站的结构语义随着线索的呈现,使之成为一种标记语言而非编程语言。
    </p>

</body>
</html>
上一节: JQuery_属性
此页面最后编辑于2022年8月25日 (星期四) 11:29。