主な問題は、あなただけのHTML要素ではなく、要素のテキストコンテンツを構成する個々の文字にスタイルを適用することができるということです。
は、これは、あなたがしている「未定義」エラーを取得している理由... backgroundColor
は、個々の文字の上に存在していないstyle
プロパティの戻り値を指し、undefined
に設定することはできませんです。
最初に、強調表示する文字を別の要素にラップする必要があります(ここでは<span>
が最適です)。<span>
の内容を強調表示することができます。
あなたは、ボタンの各クリックだけ次の文字やハイライトは次の文字を含むように拡張されなければならないので、私は下記の者の両方のためのソリューションを持っている場合を強調すべきかどうかについて、正確には明らかでありませんでした。詳細な説明については、インラインコメントを参照してください:
溶液#1(一度に単一の文字を強調表示)
// Get DOM reference to paragraph (not contents of paragraph)
var x = document.getElementById("temp");
// Get DOM reference to button so we can wire it up to
// an event handler in JS (not via inline event handling attributes).
var btn = document.getElementById("btn");
// Set up event handler:
btn.addEventListener("click", selector);
var i = 0;
function selector() {
// Get the character to be highlighted
var char = x.textContent.charAt(i);
// Set the contents of the paragraph to a new string that has the particular character
// wrapped with a <span> that is set to use a predetermined class that does the actual
// highlighting.
x.innerHTML = x.textContent.replace(char, "<span class='highlight'>" + char + "</span>");
// Increment i until we've hit the 26th value, then reset to 0
i < 25 ? i++ : i = 0;
}
.highlight { background-color:red; }
<p id="temp">ABCDEFGHIJKLMNOPQRSTUVWXYZ</p>
<br>
<!-- There is no closing tag for input elements! -->
<input type="button" id="btn" value="SELECT">
溶液#2(次の文字を含めるように強調表示拡張)
// Get DOM reference to paragraph (not contents of paragraph)
var x = document.getElementById("temp");
// Get DOM reference to button so we can wire it up to an event handler in JS (not via inline event
// handling attributes).
var btn = document.getElementById("btn");
// Set up event handler:
btn.addEventListener("click", selector);
var i = 0;
function selector() {
// Get the character to be highlighted
var char = x.textContent.charAt(i);
// Set the contents of the paragraph to a new string that encloses all the characters
// up to and including the current one in a <span> that is set to use a predetermined
// class that does the actual highlighting.
x.innerHTML = "<span class='highlight'>" + x.textContent.replace(char, char + "</span>");
// Increment i until we've hit the 26th value, then reset to 0
i < 25 ? i++ : i = 0;
}
.highlight { background-color:red; }
<p id="temp">ABCDEFGHIJKLMNOPQRSTUVWXYZ</p>
<br>
<!-- There is no closing tag for input elements! -->
<input type="button" id="btn" value="SELECT">
あなたは、単一の文字のスタイルを設定することはできません。私は、それぞれの文字をそれぞれ「スパン」でラップし、それをスタイリングすることをお勧めします。 – evolutionxbox
チャレンジは@evolutionxboxになり、ネストされたタグの各文字をラップしないようにします。示されているinnerHTMLを考えると、それは問題ではありません。しかし、この同じコードが子孫タグで再利用される場合、このアプローチで完全に壊れてしまいます。 – Snowmonkey
@Armin 'selector()'関数は 'i'をインクリメントします。 –