【问题标题】:how to get the background color of a div inside input - JavaScript如何在输入中获取 div 的背景颜色 - JavaScript
【发布时间】:2021-03-20 14:46:39
【问题描述】:

我不知道为什么这段代码不起作用!为什么它显示警报空白?

<html lang="en">

    <head>
        <title>Document</title>
        <style>
            #dd{
                height: 300px;
                width: 300px;
                background-color: mediumblue;
                color: white;
            }

        </style>
    </head>

    <body>
        <label>Color </label><input id="in1" type="text">
        <hr>

        <div id="dd">
    </div>

        <script>
            var colorTextBox = document.getElementById("in1");
            var div = document.getElementById("dd");

            div.onclick = function(){
                colorTextBox.value = div.style.backgroundColor;
        alert(div.style.backgroundColor);
            }

        </script>
       
    </body>
</html>

当点击 div 时,div 的背景颜色应该写在输入框内,并且也会显示在 alert 中。

【问题讨论】:

标签: javascript html


【解决方案1】:

有了这个,它将计算 rgb 颜色: `

    var colorTextBox = document.getElementById("in1");
                var div = document.getElementById("dd");

                div.onclick = function(){
                    //colorTextBox.value = div.style.backgroundColor;
            //alert(div.style.backgroundColor);
            
            const element = document.querySelector('#dd');
            const style = getComputedStyle(element)
            var color= style.backgroundColor;
            alert(color);
                }
    <html lang="en">

        <head>
            <title>Document</title>
            <style>
                #dd{
                    height: 300px;
                    width: 300px;
                    background-color: mediumblue;
                    color: white;
                }

            </style>
        </head>

        <body>
            <label>Color </label><input id="in1" type="text">
            <hr>

            <div id="dd">
        </div>

            <script>
                
            </script>
           
        </body>
    </html>

`

【讨论】:

    【解决方案2】:

    Element.style.&lt;style&gt; 只能检索内联样式。

    例如,如果您将 div 更改为 &lt;div id="dd" style="background-color: mediumblue"&gt;,则 div.style.backgroundColor 将返回 mediumblue

    要获得样式标签中定义的背景颜色,您应该改用getComputedStyle(Element)getComputedStyle(div).backgroundColor 确实有效,返回 rgb(0, 0, 205),这是 mediumblue 的 rgb 值。

    Demo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多