检测我是否单击元素中的元素 [英] Detect if I'm clicking an element within an element

查看:78
本文介绍了检测我是否单击元素中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素(让我们说id为Test的div)具有设定的高度和宽度。随机放置在这个元素中的是其他(较小的)元素(比如id的inner1,inner2,inner3),但也有空格,没有元素的空间。我希望有一个单击主元素时触发的函数,但是然后检测我是否点击了空格,如果没有,则单击一个内部元素,如果是,则返回内部元素的id。

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.

哦,内部元素是动态生成的,所以我不知道手头的id,我知道它们要么是div还是跨度......(就像例子一样,但是我将有多种类型的元素。)

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).

谢谢大家。

(感谢Xotic750的提醒我发布我的意思:))

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

我没有尝试太多,因为我不知道如何通过javascript调用检测内部点击..

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

但这是一个例子:

<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/

推荐答案

我想这就是你是什么意思?

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>

这篇关于检测我是否单击元素中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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