我试图通过使用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 = ...行存在问题。我的问题是什么?
答案 0 :(得分:1)
<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);
此致 阿肖克