家长可以在点击时更改颜色,但孩子不能

时间:2019-05-14 12:08:01

标签: click parent-child

每个都是通过单击的div。单击parent和parent2可以更改颜色(),但是单击child-div(some_id1,some_id2)不能更改颜色。如何避免这种情况,应单击每个div并更改颜色? 当然,以后我会添加更多div。

<style> 
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}

#some_id2{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}

#parent{
width: 150px;
height: 150px;
margin: 10px;
padding: 10px;
background-color: blue;
}

#parent2{
width: 150px;
height: 150px;
margin: 10px;
padding: 10px;
background-color: blue;
}
</style>
</head>
<body>

<input type="color" id="divbackgroundcolor" onchange="ColorChange()">

<div class="some_style" id="parent">
     <div class="some_style" id="some_id1"></div>
     <div class="some_style" id="some_id2"></div>
</div>

<div class="some_style" id="parent2"></div>

<script>
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId

for (var i = 0; i < divCount; i += 1) {
    div[i].onclick = function(e) {
        clickedDivId = this.id
    };
} 

function ColorChange(){
        var x = document.getElementById("divbackgroundcolor").value;
        document.getElementById(clickedDivId).style.backgroundColor = x;
}        
</script>

2 个答案:

答案 0 :(得分:1)

y.addEventListener('click',function(e){event.stopPropagation(); clickedDivId = this.id;

答案 1 :(得分:0)

一个非常有趣的问题。可以通过以下事实来解释这一点:父级始终是操作中被单击的父级,如果我们编辑代码以使用section标签,我们可以看到底部的节段被单击并且可以更改,但是顶部的两个子级可以被更改。项不会更改,也不会因为父项而被注册为被单击。

<style> 
    #some_id1{
    width: 50px;
    height: 50px;
    margin: 10px;
    background-color: red;
    }

    #some_id2{
    width: 50px;
    height: 50px;
    margin: 10px;
    background-color: red;
    }

    #parent{
    width: 150px;
    height: 150px;
    margin: 10px;
    padding: 10px;
    background-color: blue;
    }

    #parent2{
    width: 150px;
    height: 150px;
    margin: 10px;
    padding: 10px;
    background-color: blue;
    }
    </style>
</head>
<body>

<input type="color" id="divbackgroundcolor" onchange="ColorChange()">

<div  class="some_style" id="parent">
     <section class="some_style" id="some_id1"></section>
     <section class="some_style" id="some_id2"></section>
</div >

<section  class="some_style" id="parent2"></section >

<script>
var div = document.getElementsByTagName("section");
var divCount = div.length;
var clickedDivId

for (var i = 0; i < divCount; i += 1) {
    div[i].onclick = function(e) {
        clickedDivId = this.id
    };
} 

function ColorChange(){
        var x = document.getElementById("divbackgroundcolor").value;
        document.getElementById(clickedDivId).style.backgroundColor = x;
}        
</script>