我在点击事件中将div添加到另一个div .foobar
。
HTML
<div class='foobar'>
<p>Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p>
</div>
CSS
.foobar {
padding: 20px;
width:400px;
height:800px;
background: yellow;
}
.run {
background:blue;
color: white;
padding: 8px;
position:absolute;
}
JS
$('.foobar').on('click', function(e) {
if (e.target !== this) return;
var posX = $(this).offset().left, posY = $(this).offset().top;
$('.foobar').append('<div style="top:'+(e.pageY - posY)+'px;left:'+ (e.pageX - posX)+'px;" class="run"><p>child</p></div>');
});
我希望我可以附加div,每当我点击div .foobar
之外的任何地方,除了附加的div及其子节点。
以下是JSfiddle
答案 0 :(得分:1)
您可以检查点击是否发生在运行元素
中
$('.foobar').on('click', function(e) {
if ($(e.target).closest('.run').length) return;
var posX = $(this).offset().left,
posY = $(this).offset().top;
$('.foobar').append('<div style="top:' + (e.pageY - posY) + 'px;left:' + (e.pageX - posX) + 'px;" class="run"><p>child</p></div>');
});
&#13;
.foobar {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='foobar'>
<span>child</span>
</div>
&#13;