1

Here is an HTML/jquery code from w3s website. If you try it at: Try It W3S You will see the problem. odd rows have different opacity than even rows, this is ok, but I want the text color(or brightness) to remain the same. How to do it? I have tried it by setting: $("tr td").css("opacity","1.0"); but it didn't help.

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){

 $("tr").css("background-color", "yellow").css("opacity","1.0");

 $("tr:odd").css("opacity","0.5");
 $("tr td").css("opacity","1.0");
});
</script>
</head>
<body>

<h1>Welcome to My Web Page</h1>

<table border="1">
<tr>
  <th>Company</th>
  <th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkцp</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
</table>

</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
maximus
  • 4,201
  • 15
  • 64
  • 117

3 Answers3

3

Actually, the text-color stays the same. However, opacity always affects the whole element (backgrounds,borders,text-colors) and all it's descendants. If you want to have transparent background only, you have to use hsla or rgba colors for the background which introduce a "transparency" channel which only affects the background of that single element:

// all you need is:
$(document).ready(function(){
    $("tr:even").css("background-color","rgb(255,255,0)");
    // rgba equivalent for yellow with 50% opacity
    $("tr:odd").css("background-color","rgba(255,255,0,0.5)");
});

Your modified Example

EDIT: alternatively this question about converting RGB to RGBA is very interesting and touches the topic about opacity altering the visual representation of a color.

However you don't need javascript at all to achieve that effect, a simple css declaration will do.

Community
  • 1
  • 1
Christoph
  • 50,121
  • 21
  • 99
  • 128
3

You can do this quite simply with CSS3:

tr:nth-child(odd) {background-color: rgba(255, 255, 0, 0.5);}
designcise
  • 4,204
  • 1
  • 17
  • 13
0

This may help,

    <script>
    $( "tr:even" ).css( "background-color", "#A9D6F5" );
    $( "tr:odd" ).css( "background-color", "#ACE6CB" )
    </script>
vardhan
  • 1,377
  • 11
  • 14