使用JavaScript设置CSS边框样式

时间:2014-05-27 02:02:52

标签: javascript html css

我试图通过使用JavaScript在一系列颜色中循环来改变边框的颜色。我理解如何使用JavaScript操作大多数CSS属性,但是在操作具有多个值的CSS属性时遇到问题(即边框:#px,solid,color)

这是我的JS:

  var self = document.getElementById("self");
  var colorArray = ["red", "yellow", "blue", "green", "orange", "cyan", "gray"];
  var colorIndex = 0;

  function changeColor () {
    self.style.border = 6px solid colorArray[colorIndex];
    colorIndex++;

    if (colorIndex >= colorArray.length) {
      colorIndex = 0;
    }
  }

setInterval(changeColor,1000);

self.style.border = ...行存在问题。我的问题是什么?

3 个答案:

答案 0 :(得分:1)

丹尼尔几乎是对的。不要忘记你的css声明中属性值之间的间距。见下文。

<script type="text/javascript">
var self = document.getElementById("self");
var colorArray = ["red", "yellow", "blue", "green", "orange", "cyan", "gray"];
var colorIndex = 0;

function changeColor () {
    self.style.border = "6px solid " + colorArray[colorIndex];
    colorIndex++;

    if (colorIndex >= colorArray.length) {
        colorIndex = 0;
    }
}

setInterval(changeColor,1000);
</script>

答案 1 :(得分:0)

如果您只想更改边框的颜色,则无需使用border速记来更改边框的所有方面:

self.style.borderColor = colorArray[colorIndex];

答案 2 :(得分:0)

以下是您应该更改的内容,因为除了color之外,其他字符串值就是您的情况:

self.style.border =“6px solid”+ colorArray [colorIndex];

完整代码:

var self = document.getElementById("self");
var colorArray = ["red", "yellow", "blue", "green", "orange", "cyan", "gray"];
var colorIndex = 0;

function changeColor () {
self.style.border = "6px solid " + colorArray[colorIndex];
colorIndex++;

if (colorIndex >= colorArray.length) {
  colorIndex = 0;
}
}


setInterval(changeColor,1000);

此致 阿肖克