简体   繁体   English

如何在 javascript 中获取 div 的边框宽度/颜色?

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

I'd like to detect if a div has border.我想检测一个 div 是否有边框。 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. ele.style.borderColor始终为 null。 BTW, I can't use JQuery here.顺便说一句,我不能在这里使用 JQuery。 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 . js小提琴

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';所以你必须做一点改变: ele.style.borderColor='#666666';

I think you're getting a null because you are missing the hyphen in the middle of the property.我认为您得到的是 null 因为您缺少属性中间的连字符。 "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.由于您不能在这里使用 jquery,我将查看所有 css 边框属性以确定它是否具有边框样式、边框宽度和边框颜色等边框。

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

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