![](/img/trans.png)
[英]Change background color of a div temporarily on click and then set to a different color
[英]button click temporarily changes div background color, not permanently as intended
我有一个div,其中包含2个输入字段和按钮,可在单击时更改div的背景颜色,问题是,当我单击按钮时(每个按钮代表一种颜色),背景颜色仅改变一秒钟,不是永久的
var noteCreate =
{
noteCreateContainer : $("<article>", { id: "noteCreateContainer" }),
noteForm : $("<form>", { id: "noteFormContainer" }),
subjectField : $("<input>", { type: "text", placeholder: "Main Heading", id: "subject"}),
noteField : $("<input>", { type: "text", placeholder: "Enter your Note", id: "noteContent" }),
submitNote : $("<button>", { type: "submit", text: "post"}).click(saveFieldInput)
}
noteCreate.noteCreateContainer.appendTo("body");
noteCreate.noteForm.appendTo(noteCreateContainer);
//For each item in array create button
var noteColourArray = [];
noteColourArray[0] = "#03CEC2";
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";
//Loop through noteColourArray and create button for each item
for (var i = 0, len = noteColourArray.length; i < len; i++) {
noteCreate.noteForm.append($("<button>", {class: "colourSelect", text: noteColourArray[i] }).click(setBackgroundColour))
console.log(noteColourArray)
}
//Change background colour on click
function setBackgroundColour()
{
$("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] )
}
noteCreate.subjectField.appendTo(noteFormContainer);
noteCreate.noteField.appendTo(noteFormContainer);
noteCreate.submitNote.appendTo(noteFormContainer);
//Run upon submitting note
//Create class div that shares variables, but each own background-color
function saveFieldInput()
{
//Read input from input fields when note is submitted
var subjectInput = $("#subject").val();
console.log(subjectInput);
}
更新:我在function setBackgroundColour()
的末尾添加了return false
,该function setBackgroundColour()
似乎获得了我从本文中查找到的结果,颜色按钮从未打算用作表单提交按钮,一个单独的按钮将解决该问题
for (var i in noteColourArray) {
// build the button with pure JS just cause it's faster
var button = document.createElement('button'),
buttonText = document.createTextNode(noteColourArray[i]);
button.className = 'colourSelect';
button.appendChild(buttonText);
// append the button
noteCreate.noteForm.append(button);
}
$('.colourSelect').each(function(index, element) {
$(this).on('click', function(e) {
e.preventDefault();
$("#noteCreateContainer").css("background-color", noteColourArray[index]);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.