我需要使用click,dblclick,mouseleave,mouseenter,dragable函数动态地将“green DIV”添加到“容器”。
但 on blur 有一些错误,因为有时textarea不会被替换为div。
HTML
<div id="add" style="background:yellow; width:100px;"> add new </div>
<div id="container"> </div>
<div id="menu" style="color:red;"><b> I'm here </b></div>
<br>
CSS
#container {
width:500px;
height:500px;
background: palegoldenrod;
position: relative;
top:20px;
left: 100px;
padding: 0px;
}
.add_to_this {
background:yellowgreen;
position: absolute;
display:inline-block;
width:200px;
height:30px;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
-o-user-select: none;
}
的jQuery
function handler1() {
clearTimeout(time1);
if ($(this).find("#menu").length) {
return;
}
$('#menu').prependTo($(this));
$("#menu").css({
position: "absolute",
left: "100px"
}).show();
}
function handler2() {
time1 = setTimeout(function() {
$('#menu').appendTo('body').clearTimeout(time1);
}, 5000);
}
function handler3() {
clearTimeout(time1);
}
function handler4(){
// DIV edit
$('#edit_div').live({
click: function() {
if ($(this).children('textarea').length === 0) {
$(this).html("<textarea class='inputbox' >"+$(this).text()+"</textarea>");
$("textarea.inputbox").focus();
$("textarea.inputbox").blur(function() {
var value = $(this).val();
$("#edit_div").text(value);
});
}
}
});
}
$("#add").on({
click: function(e) {
var timestamp = Date.now();
var posx = Math.floor(Math.random() * 400);
var posy = Math.floor(Math.random() * 400);
$('#container').append(function() {
return $('<div class="add_to_this" id="' + timestamp + '" style="left:' + posx + 'px; top:' + posx + 'px; "><div id="edit_div">Click here</div></div>').click(handler1).mouseleave(handler2).mouseenter(handler3).dblclick(handler4).draggable({
containment: "#container",
scroll: false,
cursor: 'lock',
opacity: 0.55,
grid: [2, 2]
}).resizable();
});
}
});