我有基本的点击功能,可以创建一个带有文字的可拖动div。我要完成的第二个功能是让用户为div选择背景颜色。我正在使用名为SPECTRUM的颜色选择器插件。问题是,当为新div选择新的背景颜色时,新的背景颜色将应用于先前创建的div。如何继续添加具有不同背景颜色的新div? JSFIDDLE
/** Colorpicker spectrum configuration **/
$("#colorpicker").spectrum({ //spectrum config
showPaletteOnly: true,
color: 'blanchedalmond',
palette: [
["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"]
],
change: function(colorSelected) {
color = colorSelected.toHexString();
}
});
/** Add New Div with selected background **/
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
}).addClass('placement');
$('.draggable').css('background-color' , color);
});
HTML
<ol>
<li><textarea rows="4" cols="50" placeholder="Type text to append to div!"></textarea>
</li>
<li><label>Choose Div Background Color:</label>
<input type='text' id='colorpicker' /></li>
<li><input type="button" id="button" value="Create Draggable Div" />
</li>
</ol>
<div>
<div class="middle-side empty"></div>
</div>
答案 0 :(得分:2)
在这一行:
$('.draggable').css('background-color' , color);
您正在更改全部您的可拖动元素的background-color
,只将其设置为新创建的元素。试试这个:
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
})
.css('background-color' , color)
.addClass('placement');
});