javascript滑鼠點擊實現改變CSS樣式

來源:互聯網
上載者:User

javascript通過改變元素class名達到間接改變CSS樣式

CSS:

/* 字型連結樣式 */td.firstLevelMenuClass a:link {color: #3E8BAC; text-decoration: none;}/* 未訪問的連結 */td.firstLevelMenuClass a:visited {color: #FFFFFF; text-decoration: none;} /* 已訪問的連結 */td.firstLevelMenuClass a:hover {color: #FFFFFF;}    /* 滑鼠移動到連結上 */td.firstLevelMenuClass a:active {color: #FFFFFF;}/* 選定的連結 *//* 滑鼠事件背景樣式 */td.firstLevelMenuClass:hover {background-image: url(../../Public/img/menu_first_down_bg.gif); } /* 滑鼠移動到連結上 */td.firstLevelMenuClassHover{background-image: url(../../Public/img/menu_first_down_bg.gif); }td.firstLevelMenuClass{background-image: url(../../Public/img/head_menu_center.gif); }

JS:

/** 取得對應類和標籤的HTML元素* clsName:給定類名* tagName:給定的HTML元素,如果為任意 tagName='*'* */function getElementsByClassName(clsName, tagName) {    var ClassElements = [];    selElements = document.getElementsByTagName(tagName);    for (var i = 0; i < selElements.length; i++) {        if (selElements[i].className == clsName) {            ClassElements[ClassElements.length] = selElements[i];        }    }    return ClassElements;}//通過改變元素class名達到間接改變背景樣式function onFirstMenuChangeBg(e) {    //先清除已經改變的元素背景樣式    var getElements = getElementsByClassName('firstLevelMenuClassHover', 'td');    for (var i = 0; i < getElements.length; i++) {        getElements[i].className = "firstLevelMenuClass";    }    //設定滑鼠點擊元素背景樣式    e.className = "firstLevelMenuClassHover";}

HTML:

<td class="firstLevelMenuClass" id="firstLevelMenu0"  onclick="onFirstMenuChangeBg(this);" ><a href='#'>測試0</a></td><td class="firstLevelMenuClass" id="firstLevelMenu1"  onclick="onFirstMenuChangeBg(this);" ><a href='#'>測試1</a></td><td class="firstLevelMenuClass" id="firstLevelMenu2"  onclick="onFirstMenuChangeBg(this);" ><a href='#'>測試2</a></td>

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.