获取 document.activeElement.id 的样式属性

get the style property of document.activeElement.id

本文关键字:样式 属性 id document activeElement 获取      更新时间:2023-09-26

我想知道焦点元素的样式属性。 我的代码不起作用:

alert(document.activeElement.id.style.border);

但它使用以下代码显示 ID:

alert(document.activeElement.id);

有什么帮助吗?我不喜欢使用 jquery 。我正在做一个关于IE 7的项目。我知道你们很多人认为IE 7不是浏览器。

id 是相关node的属性,style也是节点的属性,所以将 id 替换为 style.borderid没有自己的属性,除了字符串固有的属性,因为它只是一个字符串)给出:

document.activeElement.style.border;

在编写时,您正在尝试访问字符串的 style 属性,该属性不存在,因此未定义。

要访问border的各个属性:

document.activeElement.style.borderStyle;
document.activeElement.style.borderWidth;

依此类推,要访问单个边界的单个属性(border-leftborder-right等):

document.activeElement.style.borderLeftWidth;
document.activeElement.style.borderLeftStyle;

而且,再一次,等等...

要回应OP留下的评论(在另一个答案中):

但是为什么这段代码:alert(document.activeElement.style.borderColor);显示空白警报?

问题可能是样式是在样式表中定义的,而 style 属性仅在元素的 style 属性中访问这些样式。在现代浏览器中,您需要查看window.getComputedStyle()以查看样式的计算呈现输出,例如:

window.getComputedStyle(document.activeElement, null).border;

Internet Explorer具有currentStyle对象的替代(在某些版本中),但是如果没有IE或Windows,我无法提供见解。下面的参考资料中有一个链接,将带您进入Microsoft的文档。

引用:

  • currentStyle对象。
  • HTMLElement.style .
  • Window.getComputedStyle() .
你需要

element.style,而不是element.id.style。元素的 ID 没有样式。

alert(document.activeElement.style.border);