这是我到目前为止尝试过的代码,但它不起作用
HTML
<button onclick="highlight('fox')">Highlight</button>
<div id="inputText">The fox went over the fence</div>
CSS
.highlight
{
background-color:yellow;
}
JS
function highlight(text)
{
inputText = document.getElementById("inputText")
var innerHTML = inputText.innerHTML
var index = innerHTML.indexOf(text);
if ( index >= 0 )
{
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML
}
}
答案 0 :(得分:0)
试试这个。它可能会被清理一下。 http://jsfiddle.net/F5NUd/9/
$('#clickme').click(function(){highlight('fox')});
function highlight(text)
{
console.log($('#inputText').text());
//inputText = document.getElementById("inputText")
var innerHTML = $('#inputText').text();
var index = innerHTML.indexOf(text);
if ( index >= 0 )
{
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
$('#inputText').html(innerHTML);
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
请你试试这个,http://codepen.io/sumitguptainfo/pen/nuFGa
<script>
function highlight(text)
{
inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML
var index = innerHTML.indexOf(text);
if ( index >= 0 )
{
innerHTML = innerHTML.substring(0,index) + "<span class='highlight' id='hightText'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;
Highlightedtext = document.getElementById("hightText");
Highlightedtext.style.backgroundColor = 'yellow';
}
}
</script>
答案 3 :(得分:0)
这就是我想出的:)
$(document).ready(function () {
var i = 0;
$('.highlightButton').on('click', function (text) {
$inputText = $('#inputText');
words = $inputText.text().match(/\w+/g);
if (i >= words.length) {
i = 0;
}
words.splice(i, 0, "<span class='highlight'>");
words.splice(i + 2, 0, "</span>");
$inputText.html(words.join(' '));
i += 1;
});
});
更新:自动字词切换:)
$(document).ready(function () {
var i,
timerId,
speed = 100, //speed in ms
higlightWord = function (text, index) {
var words = text.match(/\w+/g);
if (index >= words.length) {
return text;
}
words.splice(index, 0, "<span class='highlight'>");
words.splice(index + 2, 0, "</span>");
return words.join(' ');
};
$('.highlightButton').bind('click', function () {
$inputText = $('#inputText');
i = 0;
if (timerId) {
clearInterval(timerId);
}
timerId = setInterval(function () {
var sentence = higlightWord($inputText.text(), i);
if (sentence !== $inputText.text()) {
i += 1;
} else {
clearInterval(timerId);
}
$inputText.html(sentence);
}, speed);
});
});