javascript - 怎么为 创建的多个div 添加onclick事件然后修改CSS属性

查看:64
本文介绍了javascript - 怎么为 创建的多个div 添加onclick事件然后修改CSS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如题,我想要在鼠标点击创建的 div 时,让背景消失。但是总是在调用时出现 Cannot read property 'style' of undefined 或者只能获得循环的最后一个数。求大神讲解下为什么和怎么解决,谢谢了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        div{
            width: 50px;
            height: 50px;
            line-height: 50px;
            /*border: 1px solid #fff;*/
            color: #fff;
            background: #ccc;
            text-align: center;
            position: absolute;
            left: 0;
            top: 0;
        }
        img{
            height: 500px;
            width: 500px;
            margin-top: 0;
        }

    </style>
</head>
<body>
    <img src="images/pic.jpg">
    <script type="text/javascript">
        window.onload =function(){
            var aDiv = document.getElementsByTagName("div");
        
            for(var i =0; i< 100; i++){
                document.body.innerHTML += "<div>"+i+"</div>";
                aDiv[i].style.left = (i%10)*50 + "px";
                aDiv[i].style.top = Math.floor(i/10)*50 + "px";
                
                // aDiv[i].onclick = function(){
                //     aDiv[i].style.color = 'yellow';        // Cannot read property 'style' of undefined
                // }

                // (function(m){
                //     aDiv[m].onclick = function(){
                    
                //         aDiv[m].style.color = 'red';    //这里只能获得循环的最后一个数
                    
                // }
                // })(i)
            }
        }
    </script>
</body>
</html>

解决方案

for (var j = 0; j < aDiv.length; j++) {

                aDiv[j].onclick = function () {
                    this.style.opacity = 0;
                }
            }

你在for循环外面加上这段代码,就可以实现点击盒子,背景消失的效果了

这篇关于javascript - 怎么为 创建的多个div 添加onclick事件然后修改CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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