【问题标题】:Can't change more then one 1 button color with a color picker不能使用颜色选择器更改超过 1 个按钮的颜色
【发布时间】:2018-03-07 14:52:34
【问题描述】:

我在这里有一个代码,它允许我从边栏或带有颜色选择器的按钮等元素中更改颜色。 数据保存在本地存储中。

发生的奇怪事情是这段代码只允许我更改同一项目之一的颜色。例如。在一个有 5 个按钮的页面上。只有一个按钮改变颜色,其他按钮保持自己的颜色。但我想让所有 5 个按钮都被更改

这是我使用 html 制作的示例,您可以在其中看到 3 个按钮中的 1 个刚刚获得颜色:https://codepen.io/anon/pen/pLzvNO?editors=1010

/*Set your own color*/
var jscolor;
var defaultColor = (localStorage.getItem("color")) ? localStorage.getItem("color"): "#0078c0";

window.addEventListener("load", startup, false);
function startup() {
  jscolor = document.querySelector(".jscolor");
  if (jscolor) {
    jscolor.value = defaultColor;
    jscolor.addEventListener("input", updateFirst, false);
    jscolor.addEventListener("change", updateAll, false);
    jscolor.select();
  }
  refreshSidebar(defaultColor);
}

function updateFirst(event) {
  refreshSidebar(event.target.value);
}

function refreshSidebar(color) {
  var side = document.querySelector(".themecolor");
  var text = document.querySelector(".onlyTextColor");
  var background = document.querySelector(".background");
  if (side, text, background) {
    side.style.backgroundColor = color;
    text.style.color = color;
    background.style.backgroundColor = color;
  }
}

function updateAll(event) {
    $(".themecolor, .background,").each(function(){
     localStorage.setItem('color', event.target.value);
    if ($(this).hasClass("onlyTextColor"))
      {
          $(this).css('color', event.target.value);
      }
    else{
      $(this).css('background-color', event.target.value);
    }
  })
}

【问题讨论】:

  • 你也可以发布相关的html吗?
  • 我同意@DanielMemije。如果没有 HTML,这个问题很难回答,因为我们不知道您的 DOM 元素是什么,因此我们不知道我们正在帮助您与之交互的内容,代码列出了 id 和类,但 css 类可以应用于任何东西并且 ID 没有定义元素/对象
  • 对不起,这是我用 html 制作的示例,您可以在其中看到 3 个按钮中的 1 个刚刚获得颜色:codepen.io/anon/pen/pLzvNO?editors=1010

标签: javascript jquery html color-picker jscolor


【解决方案1】:

整个问题在于您的 updateAll 函数。

通过使用$(this) 选择器,您就是selecting your current HTML element

根据jQuery Docs

.each()

类型:函数(整数索引,元素元素

为每个匹配元素执行的函数。

因此您可以修改您的updateAll 函数以匹配以下内容

function updateAll(event) {
  // Set color to local storage
  localStorage.setItem('color', event.target.value);
  // Loop through elements with 'themecolor' or 'background' classes
  $(".themecolor, .background").each(function(index, element){     
    // If element needs only text color change
    if($(element).hasClass("onlyTextColor")){
      // Change text color
      $(element).css('color',event.target.value)
    }
    // Else
    else{ 
      // Change background color
      $(element).css('background-color', event.target.value);
    }    
  });
}

【讨论】:

  • 好的,谢谢你让我知道这一点,但它仍然只改变了 1 个按钮的颜色,而不是在同一个 html 页面中的所有按钮
  • mmh 是的,我知道你是对的。然后我认为我的 HTML 中出了点问题。每次我只看到第一个获得颜色的按钮。所有其他按钮都没有颜色。我使用了您的代码,并在您的 codepen 中看到它确实有效。 (Thx btw)但我不明白,我认为需要调试..
猜你喜欢
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
相关资源
最近更新 更多