• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

JavaScript如何使用事件代理高亮显示表格行代码

JavaScript 水墨上仙 2941次浏览

JavaScript通过事件代理高亮显示表格行代码

<!DOCTYPE html>
<html>
<head>
<title>Highlight Rows</title>
<style type="text/css">
    table {
        background-color: lightgreen;
    }
    #third {
        background-color: yellow;
    }
</style>
</head>
<body>
<!-- Demonstrating "Event Delegation" to highlight table' rows 
    on mouseover. 
    Arguments can be passed via the delegate. 
My site:andrew.dx.am -->
<table id="thetable" summary="highlight demo">
    <tr><td>Just one</td><td>.. no another</td></tr>
    <tr><td>Second</td><td>.. no another</td></tr>
    <tr id="third"><td>A third</td><td>.. no another</td></tr>
    <tr><td>Fourth for luck</td><td>.. no another</td></tr>
</table>
<script type="text/javascript">
var addEvent = function (elem, eventType, func) {
    if ( elem.addEventListener )
        addEvent = function (elem, eventType, func) {
            elem.addEventListener(eventType, func, false);
        };
    else if ( elem.attachEvent )
        addEvent = function (elem, eventType, func) {
            elem.attachEvent('on' + eventType, func);
        };
    addEvent(elem, eventType, func);
};
var delegateEvent = function (elem, childElems, eventType, func, args) {
    addEvent(elem, eventType, function (e) {
        var evt = e || window.event;
        var elem = evt.target || evt.srcElement;
        if ( elem.nodeName.toLowerCase() == childElems.toLowerCase() ) {
            func(elem, args);
        }
    });
};
function highlightRows(obj, args) {
    if (args && args.over) {
        obj.prevColour = obj.parentNode.style.backgroundColor;
        obj.parentNode.style.backgroundColor = args.colour;
        if (args.index && obj.title == "")
            obj.title = "Row " + obj.parentNode.rowIndex;
    } else {
        obj.parentNode.style.backgroundColor = "";
        if (obj.title.indexOf("Row ") + 1)
            obj.title = "";
    }
}
function init() {
    delegateEvent(document.getElementById('thetable'), 'td', 'mouseover',
                  highlightRows, {'colour': 'lightblue', 'over': true, 
                    'index': true});
    delegateEvent(document.getElementById('thetable'), 'td', 'mouseout',
                  highlightRows, {'over': false});
}
addEvent(window, 'load', init);
</script>
</body>
</html>


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明JavaScript如何使用事件代理高亮显示表格行代码
喜欢 (0)
加载中……