我有一个关于 JavaScript 的问题。我有以下 html 代码,4 个按钮,2 个用于突出显示颜色,1 个用于清除所选颜色,1 个用于清除所有颜色。
当用户使用鼠标突出显示文本并单击“红色”按钮时,例如我的名字是约翰,所选文本将突出显示为红色(假设有一个名为“红色”的类)。
例如
// 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>
当用户单击“全部清除”按钮时,所有颜色都会消失。
当用户选择彩色文本时,例如“清除”按钮(我不知道这部分)我的名字叫约翰,然后点击“清除”,颜色就会消失。
例如
// 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>
最佳答案
我建议使用 jQuery 来解决跨浏览器问题并更优雅地处理这个问题。但在纯 JS 层面上,一种粗略的做法是:
function clear_colour() {
targetHTML = document.getElementById('text');
targetHTML.innerHTML = targetHTML.innerText ? targetHTML.innerText : targetHTML.textContent;
}
注意: innerText
仅适用于 IE。其他浏览器(基于 FF/Webkit)使用符合标准的 textContent
属性。
使用 jQuery:
function clear_colour() {
var clearText = $('#text span.colour').text();
$('#text').html(clearText);
}
关于javascript - 如何通过Javascript检查最近的html标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6737837/