[英]border of one div to be the color of another with javascript
我有这个表格和几个div。 问题是,一个div的颜色是用javascript随机设置的,另一个div的边框必须与第一个div处于一种颜色。 它变得更加复杂,因为几个div具有一个类名。 基本上,我的意思是一所房子应该是一种颜色,而“屋顶”取决于内容,该内容的颜色是使用js随机设置的。 为此工作了很长时间,但似乎没有解决办法(
我想,JavaScript应该看起来像这样
document.getElementByClassName("roof").style.border-bottom-color = document.getElementByClassName("contents").style.background-color;
如果您想保留“纯” JS,请查看以下方法:
document.getElementsByClassName("roof")[0].style.borderBottomColor =
getStyle(document.getElementsByClassName("contents")[0], 'backgroundColor');
function getStyle(el,styleProp)
{
if (el.currentStyle)
return el.currentStyle[styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
请注意, getElementsByClassName
返回具有所有给定类名的一组元素。 要访问所有它们并用随机颜色填充元素边框,我可以建议您像这样循环遍历它们:
var yourElements = document.getElementsByClassName('className');
for(var i=0; i<yourElements.length; i++) {
yourElements[i].style.borderColor= "#RANDOM_COLOR";
}
先进的技术是使用jQuery,JustAnil给出了正确的答案。
希望能帮助到你。 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.