<body>
<!-- 父对象 -->
<div id="father">
<!-- 子对象 -->
<div id="son"></div>
</div>
</body>
<style>
#father
{
width: 200px;
height: 200px;
background-color: #000;
overflow:hidden;
}
#son
{
width: 100px;
height: 100px;
margin: 50px 0px 0px 50px;
background-color: #eee;
}
</style>
<script>
/**
* 冒泡:由目标节点,向父节点冒泡
*/
var father = document.getElementById('father');
var son = document.getElementById('son');
father.addEventListener('click',function(e)
{
console.log('father')
})
son.addEventListener('click',function(e)
{
console.log('son')
})
/**
* 输出:son father
*/
/**
* 禁止冒泡
*/
father.addEventListener('click',function(e)
{
console.log('father')
})
son.addEventListener('click',function(e)
{
console.log('son')
e.stopPropagation();
})
/**
* 输出:son
*/
/**
* 事件委托:在父对象上侦听所有子对象事件,并判断是哪个元素发出的
*/
father.addEventListener('click',function(e)
{
console.log(e.target.id) //输出:son
})
</script>
网友评论