且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个不同点击两个div,一个在另一个之上

更新时间:2022-10-22 20:29:22

The best way to detect which element was clicked is to analyze target of event ( click event ). I have prepared small example for this case. You can see it in code below.

function amIclicked(e, element)
{
    e = e || event;
    var target = e.target || e.srcElement;
    if(target.id==element.id)
        return true;
    else
        return false;
}
function oneClick(event, element)
{
    if(amIclicked(event, element))
    {
        alert('One is clicked');
    }
}
function twoClick(event, element)
{
    if(amIclicked(event, element))
    {
        alert('Two is clicked');
    }
}

This javascript method can be called before you execute your script

Example

<style>
#one
{
    width: 200px;
    height: 300px;
    background-color: red;
}
#two
{
    width: 50px;
    height: 70px;
    background-color: yellow;
    margin-left: 10; 
    margin-top: 20;
}

</style>



<div id="one" onclick="oneClick(event, this);">
    one
    <div id="two" onclick="twoClick(event, this);">
        two
    </div>
</div>

I hope this helps.