[英]Is it possible to change the background color and back to the original in plain javascript every time i click a button?
除非我使用jQuery,否则我似乎看不到Google上的任何结果,而且我不确定jQuery和javascript是否可以协同工作。
Try using data-*
attribute to store color replacement, original background color of button
element or initial
setting; 尝试使用
data-*
属性存储颜色替换, button
元素的原始背景颜色或initial
设置; JSON.parse()
, JSON.stringify()
, Array.prototype.reverse()
to toggle data-*
attribute values that set background
of input type="button"
element; JSON.parse()
, JSON.stringify()
, Array.prototype.reverse()
切换设置input type="button"
元素background
的data-*
属性值; onclick
event. onclick
事件。
Not certain if requirement is to toggle background color, or reset to original color once ? 不确定是否需要切换背景颜色或一次重置为原始颜色?
<input type="button" value="button" data-colors='["blue", "buttonface"]' onclick="this.style.background = JSON.parse(this.dataset.colors)[0]; this.dataset.colors = JSON.stringify(JSON.parse(this.dataset.colors).reverse());" />
jQuery will not conflict with javascript, it is just a js library :) So you can use the selector.css()
of jquery or, in standard js i think it is (element).style.background = color
. jQuery不会与javascript冲突,它只是一个js库:)因此,您可以使用jquery的
selector.css()
,或者在标准js中,我认为它是(element).style.background = color
。
I recommend using jQuery. 我建议使用jQuery。 Here is a SIMPLE jQuery way to do it:
这是一种简单的jQuery方式:
$("#button").click(function(){
$("#tochange").css("background-color", "colorhex");
});
If you want to swap colors you could, for example, add a variable. 如果要交换颜色,则可以添加一个变量。
var x;
$("#button").click(function(){
if(x==0){
$("#tochange").css("background-color", "colorhex");
x= 1;
}
else{other way round}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.