// by Real-Time Search in JavaScript //http://osvaldas.info/real-time-search-in-javascript 'use strict'; // search & highlight ;( function( $, window, document, undefined ) { var $container = $( '.faq' ); if( !$container.length ) return true; var $input = $container.find( 'input' ), $notfound = $container.find( '.faq__notfound' ), $items = $container.find( '> ul > li' ), $item = $(), itemsIndexed = []; $items.each( function() { itemsIndexed.push( $( this ).text().replace( /\s{2,}/g, ' ' ).toLowerCase() ); }); $input.on( 'keyup', function( e ) { if( e.keyCode == 13 ) // enter { $input.trigger( 'blur' ); return true; } $items.each( function() { $item = $( this ); $item.html( $item.html().replace( /<span class="highlight">([^<]+)<\/span>/gi, '$1' ) ); }); var searchVal = $.trim( $input.val() ).toLowerCase(); if( searchVal.length ) { for( var i in itemsIndexed ) { $item = $items.eq( i ); if( itemsIndexed[ i ].indexOf( searchVal ) != -1 ) $item.removeClass( 'is-hidden' ).html( $item.html().replace( new RegExp( searchVal+'(?!([^<]+)?>)', 'gi' ), '<span class="highlight">$&</span>' ) ); else $item.addClass( 'is-hidden' ); } } else $items.removeClass( 'is-hidden' ); $notfound.toggleClass( 'is-visible', $items.not( '.is-hidden' ).length == 0 ); }); })( jQuery, window, document );
body { padding: 5rem 1.25rem; /* 80 20 */ } .container { width: 100%; max-width: 640px; /* 960 */ margin: 0 auto; } .container p { line-height: 1.6; } .faq input { width: 100%; font-size: 20px; display: block; padding: 0 20px; margin-bottom: 40px; } .faq .highlight { background-color: #fffd77; } .faq > ul > li.is-hidden { display: none; } .faq > ul > li h2 { font-size: 24px; } .faq > ul > li h2:hover, .faq > ul > li h2:focus, .faq > ul > li.is-active h2, .faq > ul > li:target h2 { color: #a664b7; } .faq > ul > li.is-active > div, .faq > ul > li:target > div { display: block; margin-top: 10px; } .faq__notfound { font-size: 20px; display: none; } .faq__notfound.is-visible { display: block; }
<div class="container" role="main"> <div class="faq"> <input type="search" value="" placeholder="検索するキーワード" /> <ul> <li id="faq-1"> <h2>東京</h2> <div> <p>東京は、江戸幕府の所在地の江戸を1868年9月に改称したものである。 「東京」という名称を用いる構想は江戸時代後期の佐藤信淵の書にあり、大久保利通がその書の影響を受けつつ「東京」とすることを建言した。 1869年2月11日1878年(明治11年)に府制を施行[1]、「東京府」となった。</p> </div> </li> <li id="faq-2"> <h2>大阪</h2> <div> <p>「大坂」という地名は、元は大和川と淀川(現在の大川)に間に南北に横たわる上町台地の北端辺りを指し、古くは摂津国東成郡に属した。</p> </div> </li> <li id="faq-3"> <h2>京都</h2> <div> <p>東アジアでは古来、歴史的に「天子の住む都」「首都」を意味する普通名詞として京(きょう)、京師(けいし)が多く使用されていた。西晋時代に世宗(司馬師)の諱である「師」の文字を避けて京都(けいと)と言うようになり、以後は京、京師、京都などの呼び名が用いられた。</p> </div> </li> </ul> <div class="faq__notfound"><p>キーワードが見当たりません。他のキーワードをお試し下さい</p></div> </div> </div>