Javascript change color of text and background to input value

前端 未结 3 933
慢半拍i
慢半拍i 2020-12-03 15:38

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 backgrou

相关标签:
3条回答
  • 2020-12-03 16:11
    document.getElementById("fname").style.borderTopColor = 'red';
    document.getElementById("fname").style.borderBottomColor = 'red';
    
    0 讨论(0)
  • 2020-12-03 16:12

    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:

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

    Unobtrusive 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.

    Your function changeBackground sets 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.

    CSS

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

    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

    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

    Source: 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.

    Update: as pointed out by @Ian

    Hex can be either 3 or 6 characters long

    Source: 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.

    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.

    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

    Here is a further modification that will allow colours by name along 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

    0 讨论(0)
  • 2020-12-03 16:30

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

    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:

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

    DEMO: 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 onchange allows you to change the color based on the input.

    0 讨论(0)
提交回复
热议问题