【问题标题】:HTML changing div color. Code not workingHTML 更改 div 颜色。代码不起作用
【发布时间】:2015-02-26 15:21:15
【问题描述】:

我想通过单击更改#demo 边框颜色,但仅在未给出css颜色时才会更改。我想将我的#demo div 边框颜色从透明更改为红色。请帮帮我:)

    <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Paslėpti daiktai</title>
    <link type="text/css" rel="stylesheet" href="stylesheet.css" />
    <script>
        function myFunction() {
            document.getElementById("demo").style.color = "red";
        }
    </script>
</head>

<body>
<div class="pagrindas">
    <img src="http://i.imgur.com/MxRlCi1.jpg" />
    <div id="demo" onclick="myFunction()" class="daiktas"></div>
</div>
</body>

</html>

CSS:

.pagrindas {
    position: relative;
}

.daiktas {
    width:50px;
    background-color: transparent;
    border:3px solid;
    border-radius: 100%;
    position:relative;
    left:195px;
    top:7px;
    padding:0px;
    margin:0px;
    height:50px;
}

img {
    position: absolute;
    top: 0px;
    left: 0px;
}

【问题讨论】:

  • color 更改文本颜色...而不是边框​​颜色
  • 什么会改变边框颜色?因为这在css中没有写入边框颜色时有效。
  • @Paulie_D 这是真的。但这个问题比看起来更有趣。 OP 提出的问题是为什么如果 border-color 没有在 CSS 中设置 ,那么设置 color 的行为类似于 border-color
  • 当然很明显应该设置borderColor而不是颜色,不明显为什么如果我设置color=red我的边框也会变成红色。
  • @dfsq 我看到你在我之前找到了参考资料。我在 MDN 上找东西

标签: javascript html css colors


【解决方案1】:

非常有趣的问题。根据W3C specification上的border-color属性:

如果一个元素的边框颜色没有用边框属性指定,用户代理必须使用元素的'color'属性的值作为边框颜色的计算值。

这就是为什么在代码中设置document.getElementById("demo").style.color = "red" 也会使边框变红的原因。

在您的情况下,CSS 规则 border: 3px solid; 没有定义 border-color 属性,只有 border-styleborder-width,因此观察到的行为。

【讨论】:

  • 这让currentColor 非常有用。
【解决方案2】:

你的脚本几乎是正确的尝试使用这个

    <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Paslepti daiktai</title>
    <link type="text/css" rel="stylesheet" href="stylesheet.css" />

    <script>
        function myFunction() {
            var element = document.getElementById('demo');
            element.style = "border-color: red;"
        }
    </script>
</head>

<body>
<div class="pagrindas">
    <img src="http://i.imgur.com/MxRlCi1.jpg" />
    <div id="demo" onclick="myFunction()" class="daiktas" onclick="myFunction()" style=""></div>
</div>
</body>

</html>

在您的脚本中,您提到它是颜色,但对于边框,我们将其称为 边框颜色。

css中的颜色用于字体着色。

【讨论】:

    【解决方案3】:

    使用

    document.getElementById("demo").style.borderColor
    

    而不是

    document.getElementById("demo").style.color
    

    当然 .color 改变文本颜色但不改变边框颜色。

    http://www.w3schools.com/jsref/prop_style_bordercolor.asp

    【讨论】:

      【解决方案4】:

      根据答案,您可以在此处找到一个工作示例:

      http://jsfiddle.net/649xuofp/

      function myFunction() {
          var element = document.getElementById('demo');
          document.getElementById("demo").style.borderColor = "red";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-08
        • 2018-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        • 2012-02-13
        相关资源
        最近更新 更多