【问题标题】:Is it possible to change the background color and back to the original in plain javascript every time i click a button?每次单击按钮时,是否可以更改背景颜色并以纯 javascript 变回原始颜色?
【发布时间】:2016-05-01 05:23:17
【问题描述】:

除非我使用 jQuery,否则我似乎在 google 上看不到任何结果,而且我不确定 jQuery 和 javascript plain 是否可以一起使用。

【问题讨论】:

  • 是的,应该可以。可以包括 htmlcssjs 在 Question 中尝试过吗?
  • 澄清...... jQuery是一个javascript库。它简化了与dom的交互......所以它不会与任何本机脚本冲突

标签: javascript background background-color


【解决方案1】:

jQuery 不会与 javascript 冲突,它只是一个 js 库 :) 所以你可以使用 jquery 的 selector.css() 或者,在标准 js 中我认为它是 (element).style.background = color

我推荐使用 jQuery。这是一个简单的 jQuery 方法:

  $("#button").click(function(){ 
   $("#tochange").css("background-color", "colorhex");
  });

如果您想交换颜色,例如,可以添加一个变量。

var x;
$("#button").click(function(){
if(x==0){
    $("#tochange").css("background-color", "colorhex"); 
    x= 1;
 } 
 else{other way round} 
});

【讨论】:

    【解决方案2】:

    尝试使用data-*属性存储颜色替换,button元素的原始背景颜色或initial设置; JSON.parse()JSON.stringify()Array.prototype.reverse() 切换设置backgroundinput type="button" 元素的data-* 属性值; onclick 事件。

    不确定是否需要切换背景颜色,或重置为原始颜色一次?

    <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());" />

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2017-08-02
      • 2014-10-10
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多