简体   繁体   中英

How can I get a div's border width/color in javascript?

I'd like to detect if a div has border. If so, I'd like to change the border color to gray. Here's my code but does not work.

var ele = document.get...;
if(ele.style.borderColor)
{
   ele.style.borderColor='666666';
}

The ele.style.borderColor is always null. BTW, I can't use JQuery here. Could someone help?

var ele = document.getElementById('a'),
    style = window.getComputedStyle(ele, null),
    sides = ['top', 'right', 'bottom', 'left'],
    maxBorder = 0;

for (var i = 0, length = sides.length; i < length; i++) {
    maxBorder = Math.max(maxBorder, parseInt(style.getPropertyValue('border-' + sides[i] + '-width')));
}

if (maxBorder) {
    ele.style.borderColor = '#666666';
}

jsFiddle .

You could just set the border color, and don't try to read any property.

If the element has no border, setting the color won't have any effect.

The error you have made is that you haven't specified the '#' sign before the color hex code
So You will have to make a little change: ele.style.borderColor='#666666';

I think you're getting a null because you are missing the hyphen in the middle of the property. "border-color"

Since you can't use jquery here I would look at all the css border properties to determine if it has a border such as border-style, border-width and border-color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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