私はjavascriptに関する質問があります。私は次のHTMLコード、4つのボタン、色を強調表示する2、選択した色をクリアするには1、すべての色をクリアするには1を持っています。Javascriptで最も近いhtmlタグをチェックするには?
ユーザーがマウスを使用してテキストを強調表示し、「赤」ボタンをクリックすると、私の名前はJohnです、選択されたテキストは赤色にハイライトされます(「赤」というクラスがあるとします)。
// Before select the text and click the button
<p id='text'>
My name is John,
I live in ABC and I have a car.
I like to play TV game.
</p>
// After select the text and click the button
<p id='text'>
<span class='red'>My name is John</span>,
I live in ABC and I have a car.
I like to play TV game.
</p>
ユーザーが[すべてクリア]ボタンをクリックすると、すべての色が消えます。
[クリア]ボタン(この部分はわかりません)では、ユーザーが色付きのテキストを選択したときなど、私の名前はJohnですし、「クリア」をクリックすると色が消えます。
// Before select the color-ed text and click the button
<p id='text'>
<span class='red'>My name is John</span>,
I live in ABC and I have a car.
I like to play TV game.
</p>
// After select the color-ed text and click the button
<p id='text'>
My name is John,
I live in ABC and I have a car.
I like to play TV game.
</p>
誰でも手伝ってもらえますか?ありがとうございました。
// javascript
function colour(colour) {
var selectTxt =
window.getSelection() ||
document.getSelection() ||
(document.selection ? document.selection.createRange().text : ''),
targetHTML = document.getElementById('text');
targetHTML.innerHTML =
targetHTML.innerHTML.replace(
RegExp(selectTxt),
'<span class="colour">'+selectTxt+'</span>');
}
function clear_colour() {
// I don't know how to do in here??
}
function clear_colour_all() {
var para = document.getElementById('text');
para.innerHTML = 'My name is John, I live in ABC and I have a car. I like to play TV game.';
}
// HTML
<input type="button" onclick="colour('red')" value='red'/>
<input type="button" onclick="colour('yellow')" value='yellow'/>
<input type="button" onclick="clear_colour()" value='Clear'/>
<input type="button" onclick="clear_colour_all()" value='Clear All'/>
<p id='text'>
My name is John,
I live in ABC and I have a car.
I like to play TV game.
</p>
お返事ありがとうございました。私はChromeで試してみて、それは仕事で、jQueryバージョンも提供してもらえますか?それは私がもっと学ぶのに役立ちます。 – John
'innerText'の代わりに' textContent'を使うとすべてのブラウザで動作する '.nodeValue'を使用します – Raynos
@Raynos:' nodeValue'は、テキストを取得するために 'targetHTML.firstChild.firstChild.nodeValue' (2番目の 'firstChild'は' span'のテキストノードです)。 – Mrchief