回答編集履歴
1
バグ修正
answer
CHANGED
@@ -1,40 +1,42 @@
|
|
1
|
-
書いてみましたが、こんな感じでしょうか
|
2
|
-
|
1
|
+
コメントで頂いた部分を取り込んだのとバグっていた部分を修正してみました。
|
3
|
-
良いのかちょっと不安ですが…
|
4
2
|
|
5
3
|
```javascript
|
4
|
+
const yougo_area = document.getElementById('sample_area');
|
5
|
+
const yougo_parts = document.getElementsByClassName('sample_part');
|
6
|
+
const input = document.getElementById('search_word');
|
7
|
+
|
6
8
|
document.getElementById("search_word").addEventListener('input', (event) => {
|
7
9
|
reset();
|
8
10
|
var sword = event.currentTarget.value; //
|
9
11
|
|
10
|
-
console.log(sword);
|
12
|
+
console.log("original search = ", sword);
|
11
13
|
|
12
14
|
if (sword == '') { return }
|
13
|
-
const regexp = new RegExp(`(?<=>)[^<>]*?(
|
15
|
+
const regexp = new RegExp(`(?<=>)[^<>]*?(.*)[^<>]*?(?=<)`, 'gi'); // タグ自体を書き換えないようにする為の正規表現
|
14
16
|
|
15
17
|
// 検索する文字列からひらがな、カタカナ表記を作る
|
16
18
|
let hiragana = katakanaToHiragana(sword);
|
17
19
|
let katakana = hiraganaToKatakana(sword);
|
18
20
|
|
19
|
-
|
21
|
+
console.log(hiragana, katakana);
|
22
|
+
console.log(`(${hiragana}|${katakana})`)
|
23
|
+
const regexp2 = new RegExp(`(${hiragana}|${katakana})`, 'gi');
|
20
24
|
|
21
|
-
|
25
|
+
[...yougo_parts].forEach(part => {
|
22
|
-
|
26
|
+
[regexp2].forEach(function (rex) {
|
23
27
|
|
24
|
-
const area = document.getElementById("sample_area");
|
25
|
-
|
28
|
+
part.innerHTML = part.innerHTML.replace(regexp, function (text) {
|
29
|
+
// console.log("replace " , text);
|
30
|
+
let orgText = text;
|
31
|
+
orgText = orgText.replace(rex, (match) => { return `<span class="highlight scroll">${match}</span>` });
|
26
32
|
|
27
|
-
area.innerHTML = area.innerHTML.replace(regexp, function (text) {
|
28
|
-
console.log("replace " , text);
|
29
|
-
let orgText = text;
|
30
|
-
orgText = orgText.replace(rex, (match) => { return `<span class="highlight scroll">${match}</span>` });
|
31
|
-
|
32
|
-
|
33
|
+
return orgText;
|
33
|
-
|
34
|
+
});
|
34
|
-
|
35
|
+
});
|
35
36
|
});
|
36
37
|
|
37
|
-
// chrome ではDOMの再描画を待たないと動かない
|
38
|
+
// chrome ではDOMの再描画を待たないと動かないようだ。
|
39
|
+
// 動作中にテキスト入力を行うと移動がキャンセルされる
|
38
40
|
setTimeout(function () {
|
39
41
|
let highlight = document.querySelector('.highlight');
|
40
42
|
if (highlight) highlight.scrollIntoView({ behavior: "smooth", block: "center" });
|
@@ -48,14 +50,14 @@
|
|
48
50
|
});
|
49
51
|
}
|
50
52
|
|
51
|
-
function
|
53
|
+
function katakanaToHiragana(str) {
|
52
54
|
return str.replace(/[\u30a1-\u30f6]/g, function(match) {
|
53
55
|
var chr = match.charCodeAt(0) - 0x60;
|
54
56
|
return String.fromCharCode(chr);
|
55
57
|
});
|
56
58
|
}
|
57
59
|
|
58
|
-
function
|
60
|
+
function hiraganaToKatakana(str) {
|
59
61
|
return str.replace(/[\u3041-\u3096]/g, function(match) {
|
60
62
|
var chr = match.charCodeAt(0) + 0x60;
|
61
63
|
return String.fromCharCode(chr);
|