javascript Javascript将文本和背景的颜色更改为输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16625618/
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-27 05:23:58  来源:igfitidea点击:

Javascript change color of text and background to input value

javascripttextcolorssubmit

提问by Holmberg

I'm going to use javascript to make a function for changing color of background, as well as text simultaneously - based on the value of a text input. I've got the background color to change, but can't manage to get the text working as well.

我将使用 javascript 来创建一个用于同时更改背景颜色和文本颜色的函数 - 基于文本输入的值。我已经改变了背景颜色,但无法使文本也能正常工作。

function changeBackground() {
    // The working function for changing background color.
    document.bgColor = document.getElementById("color").value;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = document.getElementById("color").value;
}

Looking into the code above, the code for the text document.getElementById("coltext").style.color = xworks when I input an actual color, and not the "color" value.

查看上面的代码,document.getElementById("coltext").style.color = x当我输入实际颜色而不是“颜色”值时,文本代码有效。

This is the html which of I'm referring to (I know it's horribly optimized, but it's a work in progress):

这是我所指的 html(我知道它进行了可怕的优化,但仍在进行中):

<form id="TheForm" style="margin-left:396px;">
    <input id="color" type="text" onchange="changeBackground();" />
    <br/><input id="submitColor" value="Submit" type="button" onclick="changeBackground();" style="margin-left:48px; margin-top:5px;" />
</form>

<span id="coltext">This text should have the same color as you put in the text box</span>

Obviously, and unfortunately, I can't use the code this way. But no matter have hard I try, beyond this, I reach a sort of infinite complexity. It should be a sort of easy way to resolve this, right?

显然,不幸的是,我不能以这种方式使用代码。但无论我怎么努力,除此之外,我都达到了一种无限的复杂性。这应该是一种简单的方法来解决这个问题,对吧?

回答by Xotic750

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

您问题中的代码似乎有些混乱,所以我将举一个例子来说明我认为您正在尝试做什么。

First considerations are about mixing HTML, Javascript and CSS:

首先要考虑混合 HTML、Javascript 和 CSS:

Why is using onClick() in HTML a bad practice?

为什么在 HTML 中使用 onClick() 是不好的做法?

Unobtrusive Javascript

不显眼的 Javascript

Inline Styles vs Classes

内联样式与类

I will be removing inline content and splitting these into their appropriate files.

我将删除内联内容并将它们拆分为相应的文件。

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

接下来,我将使用“click”事件并处理“change”事件,因为不清楚您想要还是需要两者。

Your function changeBackgroundsets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

您的函数changeBackground将背景颜色和文本颜色设置为相同的值(您的文本将不会被看到),因此我正在缓存颜色值,因为我们不需要在 DOM 中查找它两次。

CSS

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

jsfiddle 上

Source: w3schools

资料来源:w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

颜色值

CSS 颜色是使用十六进制 (hex) 表示法定义的,用于组合红色、绿色和蓝色颜色值 (RGB)。可以赋予其中一个光源的最小值是 0(十六进制 00)。最高值为 255(十六进制 FF)。

十六进制值写为 3 个两位数,以 # 符号开头。

Update: as pointed out by @Ian

更新:正如@Ian 所指出的

Hex can be either 3 or 6 characters long

十六进制可以是 3 或 6 个字符长

Source: W3C

资料来源:W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#' immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

数字颜色值

十六进制表示的 RGB 值的格式是一个“#”,紧跟三个或六个十六进制字符。三位数 RGB 符号 (#rgb) 通过复制数字而不是通过添加零转换为六位数形式 (#rrggbb)。例如,#fb0 扩展为 #ffbb00。这确保可以使用短符号 (#fff) 指定白色 (#ffffff) 并消除对显示颜色深度的任何依赖。

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

这是一个替代函数,它将检查您的输入是否为有效的 CSS 十六进制颜色,它将仅设置文本颜色或在无效时发出警报。

For regex testing, I will use this pattern

对于正则表达式测试,我将使用这种模式

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

但是如果您是正则表达式匹配并且想要将数字分成组,那么您将需要不同的模式

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

jsfiddle 上

Here is a further modification that will allow colours by namealong with by hex.

这是一个进一步的修改,允许按名称和十六进制颜色

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

jsfiddle 上

回答by Ian

Depending on which event you actually want to use (textbox change, or button click), you can try this:

根据您实际想要使用的事件( textboxchange或 button click),您可以尝试以下操作:

HTML:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO:http://jsfiddle.net/6pLUh/

演示:http : //jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchangeallows you to change the color based on the input.

该按钮的一个小问题是它是表单中的提交按钮。单击后,将提交表单(最终只是重新加载页面)并且 JavaScript 中的任何更改都将被重置。仅使用onchange允许您根据输入更改颜色。

回答by Ankit kumar

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';