Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

javascript - Detect if I'm clicking an element within an element

I have an element (let's say div with id "Test") with a set height and width. Randomly placed within this element are other (smaller) elements (let's say id's "inner1","inner2","inner3"), but there is also whitespace, space where no elements are. I would like to have a function that fires upon clicking the main element, but then detect wether i'm clicking whitespace, or if not, clicking an inner element and if so, return the id of the inner element.

Oh and the inner elements are dynamically generated so i don't know the id's before hand, i do know they are either div's or spans... (just as example as well, but i will have multiple types of elements).

Thanks everyone.

EDIT: (since thank you Xotic750 for reminding me to post what i mean :))

I haven't tried much since i have no idea how to call detect an inner click through the javascript..

but here is an example:

<div id="test">
    <div id="inner1"></div>
    <span id="inner2"></span>
    <div id="inner3"></div>
</div>
<style>
div#test {
    width:300px;
    height:400px;
    position:relative;
    display:block;
    border:1px solid blue;
}
div#test div, div#test span {
    display:block;
    position:absolute;
    border:1px solid red;
}
div#inner1 {
    top:15px;
    left:15px;
    height:15px;
    width:15px;
}
span#inner2 {
    top:65px;
    left:65px;
    height:15px;
    width:15px;
}
div#inner3 {
    top:155px;
    left:155px;
    height:15px;
    width:15px;
}
</style>

http://jsfiddle.net/BgbRy/2/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this is what you mean?

var test = document.getElementById('test');

function whatClicked(evt) {
  alert(evt.target.id);
}

test.addEventListener("click", whatClicked, false);
div#test {
  width: 300px;
  height: 200px;
  position: relative;
  display: block;
  border: 1px solid blue;
}

div#test div,
div#test span {
  display: block;
  position: absolute;
  border: 1px solid red;
}

div#inner1 {
  top: 15px;
  left: 15px;
  height: 15px;
  width: 15px;
}

span#inner2 {
  top: 65px;
  left: 65px;
  height: 15px;
  width: 15px;
}

div#inner3 {
  top: 155px;
  left: 155px;
  height: 15px;
  width: 15px;
}
<div id="test">
  <div id="inner1"></div>
  <span id="inner2"></span>
  <div id="inner3"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...