日期:2014-05-16  浏览次数:20321 次

js改变样式
JScript code

<script type="text/javascript">
    function yanse(){
            
            document.getElementById('picture').style.backgroundColor = '#f8f8f8';
            document.getElementById('picture').style.border = '1px solid #00a2ff';
        }
    function old(){
            document.getElementById('picture').style.backgroundColor = '#f1f1f1';
            document.getElementById('picture').style.border = '1px solid #D7D7D7';
        }
</script>


HTML code
<ul class="photos clearfix">
        <li>
            <div class="picture" id="picture" onMouseOver="yanse()" onMouseOut="old()"><span></span><a href="#"><img src="photo_1.jpg"></a></div>
            <div class="name"><a href="#">图片1</a></div>
        </li>
        <li>
            <div class="picture"><span></span><a href="#"><img src="photo_2.jpg"></a></div>
            <div class="name"><a href="#">图片2</a></div>
        </li>
        <li>
            <div class="picture"><span></span><a href="#"><img src="photo_3.jpg"></a></div>
            <div class="name"><a href="#">图片3</a></div>
        </li>
        <li>           
            <div class="picture"><span></span><a href="#"><img src="photo_4.jpg"></a></div>
            <div class="name"><a href="#">图片4</a></div>
        </li>
</ul>



 页面中id是惟一的,如果其他的class为picture的盒子使用这个函数的时候,需要命名为其他的id,在实际项目中运用太麻烦,怎么样才能达到当鼠标在任意一个class为picture的盒子上时,就改变背景色和边框颜色呢?

------解决方案--------------------
HTML code
<script type="text/javascript">
window.onload = function() {
    var ul = document.getElementsByTagName('ul');
    for (var i = 0; i < ul.length; i ++) {
        if (ul[i].className.indexOf('photos') != -1) {
            var obj = ul[i].getElementsByTagName('div');
            for (var j = 0;j < obj.length; j ++) {
                if (obj[j].className == 'picture') {
                    obj[j].onmouseover = function() {
                        this.style.backgroundColor = '#f8f8f8';
                        this.style.border = '1px solid #00a2ff';
                    }
                    obj[j].onmouseout = function() {
                        this.style.backgroundColor = '#f1f1f1';
                        this.style.border = '1px solid #D7D7D7';
                    }
                }
            }
        }
    }
}
</script>

------解决方案--------------------
HTML code

<!DOCTYPE html>
<html>
 <head>
  <title> new document </title>
 </head>
 <script type="text/javascript">
    function yanse(obj){         
            obj.style.backgroundColor = '#f8f8f8';
            obj.style.border = '1px solid #00a2ff';
        }
    function old(obj){
            obj.style.backgroundColor = '#f1f1f1';
            obj.style.border = '1px solid #D7D7D7';
        }
 </script>
 <body>
  <ul class="photos clearfix">
        <li>
            <div class="picture" id="picture" onMouseOver="yanse(this)