基本上,我希望用户点击任何 .editable 项目,这会使输入出现,复制其样式,然后如果他们点击其他任何地方,我希望输入消失并保存更改。我很难完成这项工作。我见过 solution使用 event.stopPropagation,但我不知道如何按照我的代码结构方式包含它:
$(function() {
var editObj = 0;
var editing = false;
$("html").not(editObj).click(function(){
if (editing){
$(editObj).removeAttr("style");
$("#textEdit").hide();
alert("save changes");
}
});
$(".editable").not("video, img, textarea")
.click(function(event) {
editObj = this;
editing = true;
$("#textEdit")
.copyCSS(this)
.offset($(this).offset())
.css("display", "block")
.val($(this).text())
.select();
$(this).css("color", "transparent");
});
}
copyCSS 函数来自 here
我需要区分对可编辑对象的点击和远离它的点击,即使该点击是针对不同的可编辑对象(在这种情况下它应该调用 2 个事件)。
最佳答案
试试这个:
$('body').click(function(event) {
var parents = $(event.target).parents().andSelf();
if (parents.filter(function(i,elem) { return $(elem).is('#textEdit'); }).length == 0) {
// click was not on #textEdit or any of its childs
}
});
$(".editable").not("video, img, textarea")
.click(function(event) {
// you need to add this, else the event will propagate to the body and close
e.preventDefault();
这通过检查被点击的元素或其任何父元素是否为#textEdit 来工作。
event.stopPropagation 解决方案可以这样实现:
// any click event triggered on #textEdit or any of its childs
// will not propagate to the body
$("#textEdit").click(function(event) {
event.stopPropagation();
});
// any click event that propagates to the body will close the #textEdit
$('body').click(function(event) {
if (editing) {
$("#textEdit").hide();
}
});
关于javascript - 如何检测元素的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126191/