javascript - js表格高亮问题

查看:95
本文介绍了javascript - js表格高亮问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

为什么这个js对表格第一行没作用
html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Document Object Model</title>
        <link rel="Stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <table>
            <caption>ltinerary</caption>
            <tr>
                <th>When</th>
                <th>Where</th>
            </tr>
            <tr>
                <td>June 9th</td>
                <td>Portland,OR</td>
            </tr>
            <tr>
                <td>June 10th</td>
                <td>Seattle,WA</td>
            </tr>
            <tr>
                <td>June 12th</td>
                <td>Sacramento,CA</td>
            </tr>
        </table>
        <script src="display.js"></script>
    </body>
</html>

css

body{
    font-family:"Helvetica","Arial",sans-serif;
    font-size:18pt;
    }
table{
    margin:10px;
    border:1px solid #699;
    }
caption{
    padding:0.2em;
    text-align:center;
    font-weight:bold;
    font-size:1.2em;
    }
th{
    font-weight:normal;
    font-style:italic;
    text-align:left;
    border:1px dotted #669;
    background-color:#9cc;
    color:#000;
    }
th,td{
    width:10em;
    padding:0.5em;
    }

js

function heightlightRows(){
    if(!document.getElementsByTagName) return false;
    var rows = document.getElementsByTagName("tr");
    for(var i=0; i<rows.length; i++){
        rows[i].onmouseover = function(){
            this.style.fontWeight = "bold";
        }
        rows[i].onmouseout = function(){
            this.style.fontWeight = "normal";
        }
    }
}
window.onload = heightlightRows;

解决方案

因为你在css里写死了th的font-weight是normal,而你在js里只是改变tr的font-weight为bold,所以不起作用。改成这样就可以了:

for (var i = 0; i < rows.length; i++) {
  rows[i].onmouseover = function() {
    var ths = this.getElementsByTagName("th");
    for (var j = 0; j < ths.length; j++) {
      ths[j].style.fontWeight = 'bold';
    }
    this.style.fontWeight = "bold";
  }
  rows[i].onmouseout = function() {
    var ths = this.getElementsByTagName("th");
    for (var j = 0; j < ths.length; j++) {
      ths[j].style.fontWeight = 'normal';
    }
    this.style.fontWeight = "normal";
  }
}

这篇关于javascript - js表格高亮问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆