提问者:小点点

如何在Input-JavaScript中获取div的背景颜色


我不知道为什么这个代码不能工作!为什么显示警报空白?

<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的背景颜色应该写在输入框中,并且也显示在警报中。


共2个答案

匿名用户

有了这个,它就会计算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>

匿名用户

element.style.