简体   繁体   English

一个div的边框是使用javascript的另一个的颜色

[英]border of one div to be the color of another with javascript

I have this form and several divs in it. 我有这个表格和几个div。 The matter is, that color of one div is set with javascript, randomly, and border of another div has to be in one color with first one. 问题是,一个div的颜色是用javascript随机设置的,另一个div的边框必须与第一个div处于一种颜色。 It gets even more complicated, because several divs have one class names. 它变得更加复杂,因为几个div具有一个类名。 Basically, what I mean here is that one house should be of one color, and "roof" depends on content, color of which is set randomly with js. 基本上,我的意思是一所房子应该是一种颜色,而“屋顶”取决于内容,该内容的颜色是使用js随机设置的。 worked on this for quite a long time, but seem to have no solution( 为此工作了很长时间,但似乎没有解决办法(

I guess, javascript should look something like this 我想,JavaScript应该看起来像这样

document.getElementByClassName("roof").style.border-bottom-color = document.getElementByClassName("contents").style.background-color;

my jfiddle with html and css 与HTML和CSS的jfiddle

If you'd like to keep "Pure" JS, take a look on this approach: 如果您想保留“纯” 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];
}

Please notice, that getElementsByClassName returns a set of elements which have all the given class names. 请注意, getElementsByClassName返回具有所有给定类名的一组元素。 To access all of them and fill in elements border with ramdom color i can advice you to go in loop throuth them like: 要访问所有它们并用随机颜色填充元素边框,我可以建议您像这样循环遍历它们:

var yourElements = document.getElementsByClassName('className');
for(var i=0; i<yourElements.length; i++) { 
  yourElements[i].style.borderColor= "#RANDOM_COLOR";
}

Advanced technique is to use jQuery, and correct answer was given above by JustAnil. 先进的技术是使用jQuery,JustAnil给出了正确的答案。

Hope it helps. 希望能帮助到你。 Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM