How to highlight my text

I have some text and a button. Once user clicks a button I want the text's background to change color to green and back. But nothing happens if I click the button...

Here's the JS script:

<script>
function bright(){
    kontakt = document.getElementById('kontakt');
    kontakt.bgcolor = '#A5DF00';
}
function dark(){
    kontakt = document.getElementById('kontakt');
    kontakt.bgcolor = '#000000';
}
function highlight(){       
    setTimeout(bright() , 1000);
    setTimeout(dark() , 1000);
}
</script>

I call the highlight() from the button's onclick attribute like this: onclick='highlight()' .

The text with id kontakt is always on the page.

Any clue?


According to your code, when highlight() is called it will wait for one second and then turn the background from whatever it was to green and immediately to black, as fast as it possibly can. I'm guessing that you don't see it flash green because that's faster than the browser renders or your eye can detect.

Try changing setTimeout(dark , 1000); to setTimeout(dark , 1500); .


The css property are accessible through the style property:

var kontakt = document.getElementById('kontakt');
function bright(){
    kontakt.style.backgroundColor = '#A5DF00';
}
function dark(){
    kontakt.style.backgroundColor = '#000000';
}

All CSS properties can be accessed the same way. if the property has a dash in it z-index just use the camel case notation.

Ex: kontakt.style.zIndex

you also need to update your setTimeout like so:

function highlight(){       
    setTimeout(bright , 1000);
    setTimeout(dark , 2000);
}

In your case you were calling the functions and passing whatever they return to setTimeout. You also want to change the timer for the first function to happen after a second, and the next follows one second after.


jsfiddle例子在这里根据这个SO回答修改。

<span id='kontakt' onClick="highlight(this);">Click me to see me change color and back</span>

function highlight(obj){
   var orig = obj.style.color;
   obj.style.color = '#f00';
   setTimeout(function(){
        obj.style.color = orig;
   }, 5000);
}
链接地址: http://www.djcxy.com/p/87672.html

上一篇: 如何更改HTML表格的背景颜色?

下一篇: 如何突出显示我的文字