我正在尝试设计一个突出显示系统,该系统将用于在mousehover上突出显示html表中的行。下面给出了我正在使用的代码,但是由于某些原因它无法正常工作,请帮助

<!-- Row Highlight Javascript -->
        <script type="text/javascript">
            window.onload=function()
            {
                var tfrow = document.getElementById('tfhover').rows.length;
                var tbRow=[];
                var original;
                for (var i=1;i<tfrow;i++)
                {
                    tbRow[i]=document.getElementById('tfhover').rows[i];

                    tbRow[i].onmouseover = function()
                    {
                        original = tbRow[i].style.backgroundColor;
                        this.style.backgroundColor = '#f3f8aa';

                    };
                    tbRow[i].onmouseout = function()
                    {
                        this.style.backgroundColor = original;

                    };
                }
            };
        </script>


但是,如果我将脚本更改为

<script type="text/javascript">
            window.onload=function()
            {
                var tfrow = document.getElementById('tfhover').rows.length;
                var tbRow=[];
                for (var i=1;i<tfrow;i++)
                {
                    tbRow[i]=document.getElementById('tfhover').rows[i];

                    tbRow[i].onmouseover = function()
                    {

                        this.style.backgroundColor = '#f3f8aa';

                    };
                    tbRow[i].onmouseout = function()
                    {
                        this.style.backgroundColor = '#fff';

                    };
                }
            };
        </script>


然后它可以正常工作,但麻烦的是我的表中某些行的背景为红色,以表示逾期未付款,对于此类行,当鼠标移出时,该行的背景色变回白色。当鼠标移出时,我需要能够将行的背景色恢复为原始颜色。

最佳答案

这应该工作:

window.onload = function() {
    // cache your dom queries
    var tfhover = document.getElementById('tfhover');
    var tfrow = tfhover.rows.length;
    var tbRow = [];
    for (var i=1; i<tfrow; i++) {
        // wrap your logic in a closure
        // otherwise original is not what you think it is
        (function(index) {
            var original;
            tbRow[index] = tfhover.rows[index];
            tbRow[index].onmouseover = function() {
                original = this.style.backgroundColor;
                this.style.backgroundColor = '#f3f8aa';
            };
            tbRow[index].onmouseout = function() {
                this.style.backgroundColor = original;
            };
        })(i);
    }
};

关于javascript - Javascript代码获取背景色不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18989313/

10-12 12:39
查看更多