如何在提交的输入字段中使用键入的十六进制代码创建新的div背景颜色

时间:2017-02-10 14:50:32

标签: javascript jquery html twitter-bootstrap

通过在输入字段中输入颜色,自动创建 col-md-3 引导程序div的背景颜色。用js和jQuery。

请帮助:提前致谢

<input type="text" id="input" placeholder="#333333">
<button id="save">Save</button>

Bootstrap div:

<div class="col-md-3">
/* create a div with background color on click */
</div>

这里的jquery代码:

var input = $('#input').val();
var save = $('#save');
save.on('click',function() {
/* code here.... */
});

4 个答案:

答案 0 :(得分:1)

&#13;
&#13;
// on click of the save button
$("#save").on('click',function() {
    // get the hex color from the input
    var color = $("input").val();
    // create a div
    var $div = $("<div class='color'></div>");

    // change its background-color to the hex color
    $div.css("background-color", color);

    // append it to the container
    $(".col-md-3").append($div);

   
    // SAVE TO LOCALSTORAGE CODE
    var savedColors = JSON.parse(localStorage.getItem("colors")) || []; // get the already saved array (or create a new one if nothing is saved yet)
    savedColors.push(color); // add this color to it
    localStorage.setItem("colors", JSON.stringify(savedColors)); // put it back into the local storage with this color added to it.
});
&#13;
.color {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin: 3px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" placeholder="#333333">
<button id="save">Save</button>

<div class="col-md-3">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$('.col-md-3').css( "background-color", input );

答案 2 :(得分:0)

将此行og HTML 代码从<button id="save">Save</button>更改为<button type="button" id="save">Save</button>

<强>的jQuery

save.on('click',function() {
  var input = $('#input').val();
  $('.col-md-3').css("background-color", input);
});

答案 3 :(得分:0)

此代码适用于我。输入值必须绑定到“更改”状态。事件。

&#13;
&#13;
var input; 
$('#input').on('change', function() {
  input = $(this).val();
});

var save = $('#save');
save.on('click', function() {
  $('div').css('background', input);
});
&#13;
div {
  height: 200px;
  width: 200px;
  background: green;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" placeholder="#333333">
<button id="save">Save</button>

<div class="col-md-3">
</div>
&#13;
&#13;
&#13;