Tôi có thể là quá muộn nhưng khi bạn không bao giờ đánh dấu nó như là trả lời, tôi nghĩ tôi có thể cung cấp cho nó một thử.
Nếu vấn đề của bạn là tính tương thích giữa trình duyệt, tôi sẽ tạo một phương pháp tùy chỉnh mà tôi có thể sử dụng trong hầu hết mọi trình duyệt (có nghĩa là quay lại những điều cơ bản).
Tôi thực sự đào rất nhiều để làm điều này. Tôi sử dụng một số mã từ jQuery vì tôi không muốn sử dụng jQuery nhưng vẫn có khả năng tương thích ngược mà jQuery thực hiện.
Chức năng này giải quyết câu hỏi của bạn và ở dưới cùng có một số ví dụ về cách sử dụng nó.
Chức năng này sử dụng "mô-đun mô-đun" thông qua chức năng ngay lập tức sẽ chạy ngay khi tập lệnh tải tạo phương thức KHÔNG PHẢI theo phạm vi toàn cục nhưng mở rộng chức năng của nó thông qua chức năng để thực hiện những gì bạn muốn.
// I give it a name but it can also be anonymous
(function preloadedFunctions(){
// Preseted methods.
if(window.getComputedStyle){
window.getComputedStylePropertyValue = function(element, prop){
var computedStyle = window.getComputedStyle(element, null);
if(!computedStyle) return null;
if(computedStyle.getPropertyValue) {
return computedStyle.getPropertyValue(prop);
} else if (computedStyle.getAttribute) {
return computedStyle.getAttribute(prop);
} else if(computedStyle[prop]) {
return computedStyle[prop];
};
};
}
// jQuery JavaScript Library v1.9.0
// http://www.minhacienda.gov.co/portal/pls/portal/PORTAL.wwsbr_imt_services.GenericView?p_docname=6240612.JS&p_type=DOC&p_viewservice=VAHWSTH&p_searchstring=
// For IE8 or less
else if (document.documentElement.currentStyle) {
var rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i"),
rposition = /^(top|right|bottom|left)$/,
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
window.getComputedStylePropertyValue = function(element, prop){
var left, rsLeft,
ret = element.currentStyle && element.currentStyle[ prop ],
style = element.style;
if (ret == null && style && style[ prop ]) {
ret = style[ prop ];
}
if (rnumnonpx.test(ret) && !rposition.test(prop)) {
left = style.left;
rsLeft = element.runtimeStyle && element.runtimeStyle.left;
if (rsLeft) {
element.runtimeStyle.left = element.currentStyle.left;
}
style.left = prop === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
style.left = left;
if (rsLeft) {
element.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
};
})();
tức
1.-
var borderWidth = getComputedStylePropertyValue(document.getElementsByTagName("div")[0], "border-width");
console.log(borderWidth);
2.-
var div = document.getElementById("someID");
console.log(getComputedStylePropertyValue(div, "border-width"));
[Nhận thuộc tính phần tử giả với JavaScript] (https://davidwalsh.name/pseudo-element) có một số ý tưởng. –