Javascript 在html中创建一个小颜色框

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

Create a small color box in html

javascriptjqueryhtmlcolors

提问by Saurabh Kumar

I have a lielement. Inside the lielement there are many elements like input, labels.

我有一个li元素。li元素内部有许多元素,例如input, labels

I want to put now a small color inside each li. The color will be provided dynamically. I want to have something square and on page load it fills with the color i provide. Is there something already existing?

我现在想在每个li. 颜色将动态提供。我想要一些方形的东西,在页面加载时它会填充我提供的颜色。有没有已经存在的东西?

回答by Stefan

Are you looking for something like this?

你在寻找这样的东西吗?

HTML

HTML

<div class="input-color">
    <input type="text" value="Orange" />
    <div class="color-box" style="background-color: #FF850A;"></div>
    <!-- Replace "#FF850A" to change the color -->
</div>

CSS

CSS

.input-color {
    position: relative;
}
.input-color input {
    padding-left: 20px;
}
.input-color .color-box {
    width: 10px;
    height: 10px;
    display: inline-block;
    background-color: #ccc;
    position: absolute;
    left: 5px;
    top: 5px;
}

See jsFiddlefor live example.

有关实时示例,请参阅jsFiddle

回答by Dave C

Disclaimer: I'm not familiar with CSS.

免责声明:我不熟悉 CSS。

I became annoyed with nuances of CSS and not getting the look and feel quite right and figuring out different configurations of div's. I stumbled on to something much simpler (to me and hopefully others): use SVG.

我对 CSS 的细微差别感到恼火,并且没有获得非常正确的外观和感觉,也无法弄清楚 div 的不同配置。我偶然发现了一些更简单的东西(对我和其他人来说):使用 SVG。

Here's an example of a yellow-box:

这是一个黄色框的示例:

<html>
Look at me - I'm a yellow box!
<svg width="20" height="20">
<rect width="20" height="20" style="fill:#E9E612;stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
</html>

When used with a jinja template I can configure the fill color by supplying the correct string from python:

当与 jinja 模板一起使用时,我可以通过从 python 提供正确的字符串来配置填充颜色:

<svg width="20" height="20">
<rect width="20" height="20" style="fill:{{supplied_color_str}};stroke-width:3;stroke:rgb(0,0,0)" />
</svg>

It's old school, but it's simple and gets the job done.

这是老派,但它很简单,可以完成工作。