javascript 如何使用 HTML5 和 CSS 更改按钮背景颜色 3 次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10855520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:16:43  来源:igfitidea点击:

How to change button background color 3 times with HTML5 & CSS

javascripthtmlcss

提问by Bob Mac

I am creating a table of buttons that a internal user can click on individually. I need the buttons to be able to toggle the background from White to Green to Red then back to White .... The user is internal and I can specify that this only works on Chrome. I would like to stick with basic HTML5/CSS3 and Javascript as it is more procedural and my team (we are NOT web page developers) are more likely to be able to maintain it.

我正在创建一个内部用户可以单独单击的按钮表。我需要按钮能够将背景从白色切换到绿色到红色,然后再切换回白色......用户是内部的,我可以指定这仅适用于 Chrome。我想坚持使用基本的 HTML5/CSS3 和 Javascript,因为它更加程序化,而且我的团队(我们不是网页开发人员)更有可能维护它。

Button Elements do not seem to work the same as Text or other elements. I have taken code to change other background colors but it does not work when the element is a button.

按钮元素似乎与文本或其他元素的工作方式不同。我已经使用代码来更改其他背景颜色,但是当元素是按钮时它不起作用。

My 2 basic blocking issues are:

我的 2 个基本阻塞问题是:

  1. How do you read the current background color in the onClick() routine so my code can calculate the next color?

    How do you change the style or class of a Button element so that the background color changes during or when you exit the onClick() routine?

  1. 您如何读取 onClick() 例程中的当前背景颜色,以便我的代码可以计算下一种颜色?

    您如何更改 Button 元素的样式或类,以便在您退出 onClick() 例程期间或退出时更改背景颜色?

I have seen examples that define 3 different color styles in the CSS file like this:

我见过在 CSS 文件中定义 3 种不同颜色样式的示例,如下所示:

.make-background-white { background-color: white}
.make-background-green { background-color: green}
.make-background-red   { background-color: red}

And I can use these when I initially draw the buttons. But I do not know how to 'read' the current background color in the onClick() routine nor can I change the color.

当我最初绘制按钮时,我可以使用这些。但我不知道如何在 onClick() 例程中“读取”当前背景颜色,也无法更改颜色。

MORE DETAILS

更多细节

I read from a database to find all the zip-codes around a store sorted by distance. I create a table of buttons with zip-codes as the text and this can range from 40-600 buttons. The background color shows what zip-codes are not-assigned (white background) and what zip codes are assigned (green background).

我从数据库中读取以查找按距离排序的商店周围的所有邮政编码。我创建了一个以邮政编码为文本的按钮表,这可以包含 40-600 个按钮。背景颜色显示哪些邮政编码未分配(白色背景)和哪些邮政编码已分配(绿色背景)。

Sometimes the user wants to click a few White zip codes to signal that they want to assign that code to the store.

有时,用户想要单击几个白色邮政编码来表示他们想要将该代码分配给商店。

I also want some helper buttons on the side that the user can click to automatically color/assign zip codes to the store with a 30 or 60 or 90 mile radius.

我还想要一些帮助按钮,用户可以单击这些按钮以自动为半径为 30 或 60 或 90 英里的商店着色/分配邮政编码。

I have a large Javascript Hash/associative array behind the scenes that use the zip-code as the key and this is used to create the buttons, track the distance, track which zip codes are assigned or un-assigned, etc. This is straightforward. Its the dynamically changing the button background that is throwing me off.

我在幕后有一个很大的 Javascript 哈希/关联数组,它使用邮政编码作为键,这用于创建按钮、跟踪距离、跟踪已分配或未分配的邮政编码等。这很简单. 它的动态改变按钮背景让我失望。

I did manage after three days of hacking to make something work by using Jquery with call-backs like this:

经过三天的黑客攻击,我确实设法通过使用带有回调的 Jquery 来完成一些工作:

$(".btn").click(function() {
    if ( $(this).hasClass ('make-background-white') {
        $(this).removeClass('make-background-white');
        $(this).addClass ('make-background-green');
    } else if ( $(this).hasClass('make-background-green') {
         // Remove green, add red
    } else if () {
        // Remove red, add white
    }

}

This seems to trigger the button to re-draw with the new background and works by storing a string in the "class" attribute that I can later read and manipulate. It's a call back in the middle of the rest of my more straight-forward Javascript and the other onClick() routines that use "getElementById()" cannot seem to read or manipulate the "class" attribute in the same fashion.

这似乎触发按钮使用新背景重新绘制,并通过在“class”属性中存储一个字符串来工作,我以后可以读取和操作。这是在我的其他更直接的 Javascript 和其他使用“getElementById()”的 onClick() 例程中间的回调,似乎无法以相同的方式读取或操作“class”属性。

Any help doing the above in Javascript would be appreciated.

任何在 Javascript 中执行上述操作的帮助将不胜感激。

回答by David says reinstate Monica

If your goal is to implement a background colour-cycling button, in plain JavaScript (in this case without reliance on class-names), then one possible approach is below, though it is, perhaps, over-complicated:

如果您的目标是在纯 JavaScript 中实现背景颜色循环按钮(在这种情况下不依赖于类名),那么下面是一种可能的方法,尽管它可能过于复杂:

function inArray(needle, haystack) {
    if (!needle || !haystack) {
        return false;
    }
    else {
        var notFound = -1;
        for (var i = 0, len = haystack.length; i < len; i++) {
            if (haystack[i] == needle) {
                return i;
            }
        }
        return notFound;
    }
}

function colorToggle(el, colors) {
    if (!el) {
        return false;
    }
    else {
        var colors = colors || [
            'rgb(255, 0, 0)',
            'rgb(0, 255, 0)',
            'rgb(0, 0, 255)'],
            wGCS = window.getComputedStyle,
            curColor = wGCS(el, null).backgroundColor;
        var pos = inArray(curColor, colors);
        if (pos > -1 && pos < (colors.length - 1)) {
            el.style.backgroundColor = colors[inArray(curColor, colors) + 1];
        }
        else if (pos > -1 && pos == (colors.length - 1)) {
            el.style.backgroundColor = colors[0];
        }
    }
}

var buttons = document.querySelectorAll('button.colorToggle');

for (var i = 0, len = buttons.length; i < len; i++) {
    buttons[i].style.backgroundColor = 'rgb(255, 255, 255)';
    buttons[i].onclick = function() {
        colorToggle(this, ['rgb(255, 255, 255)','rgb(0, 255, 0)','rgb(255, 0, 0)']);
    };
}?

JS Fiddle demo.

JS小提琴演示

Because of your assurance that this is only required to run in Chrome I've tested only in Chromium 18 (since I don't have Windows or Mac in order to test Google Chrome explicitly), and this does seem to do as you require.

由于您保证这仅需要在 Chrome 中运行,因此我仅在 Chromium 18 中进行了测试(因为我没有 Windows 或 Mac 来明确测试 Google Chrome),并且这似乎确实符合您的要求。

References:

参考:

回答by Vidul

Do you really need to get the CSS attribute before its change? An example without this prerequisite:

您真的需要在更改之前获取 CSS 属性吗?没有此先决条件的示例:

<html>
<head>
<script type="text/javascript">
var bg_colors = ['red', 'blue', 'green']

function change_bg_color()
{
  bg_color = bg_colors.shift();
  bg_colors.push(bg_color);
  document.getElementById("demo").style.backgroundColor=bg_color;
}
</script>
</head>
<body>

<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="change_bg_color()">change background-color</button>

</body>
</html> 

回答by kennebec

If you only need one class name at a time per button you can read/write the classname on click.

如果每个按钮一次只需要一个类名,则可以在单击时读取/写入类名。

$(".btn").click(function() {
   var c=this.className;
   if(c=='make-background-white' || c=='')this.className='make-background-red';
   else if(c=='make-background-red')this.className='make-background-green';
   else this.className='make-background-white';
}

This assumes you are starting with white background, either because all buttons start out that way(button, .make-background-white{background-color:white;color:black}), or you set their class attribute.

这假设您从白色背景开始,要么因为所有按钮都以这种方式开始(按钮,.make-background-white{background-color:white;color:black}),或者您设置了它们的类属性。

回答by Bob Mac

SUCCESS. I finally found how to access the className attribute with Javascript.

成功。我终于找到了如何使用 Javascript 访问 className 属性。

And somehow - setting the className seems to trigger the re-draw of the button.

不知何故 - 设置 className 似乎触发了按钮的重新绘制。

Below is my function I call with the onClick="zipClick('this_button', 'this_textarea')"

下面是我用 onClick="zipClick('this_button', 'this_textarea')" 调用的函数

Thank you for all the great responses.

感谢您的所有精彩回复。

    // This function does 2 things:
    //    Changes the background color of the button
    //    Calls a REST service
    function zipClick (aButtonId, aTextAreaId) {

        var lButton = document.getElementById(aButtonId);
        var lClassName = lButton.className;

        // lClassName should be something like: "btn make-background-yellow"
        //alert ("Button Class Start = " + lClassName);

        if ( lClassName.indexOf('green') > -1 ) {
            lButton.className = 'btn make-background-yellow';
        } else if ( lClassName.indexOf('white') > -1) {
            lButton.className = 'btn make-background-green';
        } else if ( lClassName.indexOf('yellow') > -1 ) {
            lButton.className = 'btn make-background-white';
        } else {
            // Should never get here but fix the class name for the next click
            lButton.className = 'btn make-background-white';
        }

        alert ("old class: " + lClassName + "\nnew class: " + lButton.className);

    }   // zipClick

回答by Bob Mac

You can achieve this by jquery setTimeOut function.By maintaining the hidden value for colors you can toggle the style

您可以通过 jquery setTimeOut 函数实现此目的。通过维护颜色的隐藏值,您可以切换样式

<script>
setTimeout(function() {   
//code to change style to button
}, 10000);
</script>