javascript

位置:IT落伍者 >> javascript >> 浏览文章

javascript获取隐藏dom的宽高 具体实现


发布日期:2019年05月03日
 
javascript获取隐藏dom的宽高 具体实现
一个隐藏的DOM是获取不到宽高的如果想要获取采用下面的方法

首先clone一个DOM设置position:absolute然后设置top为一个比较大的负值然后使其显示出来最后获取到了DOM的宽高后将其remove
具体代码如下
Js代码

复制代码 代码如下:
function getCss(elem css){
if (windowgetComputedStyle) {
return windowgetComputedStyle(elem null)[css];
}else if (elemcurrentStyle) {
return elemcurrentStyle[css];
}else {
return elemstyle[css];
}
}
function getWH(dom){
var get = function(elem){
var wh = {};
Width Heightreplace(/[^ ]+/g function(i){
var a = itoLowerCase();
wh[a] = elem[offset + i] || elem[client + i];
});
return wh;
};
if (getCss(dom display) === none) {
var nDom = domcloneNode(true);
nDomstyleposition = absolute;
nDomstyletop = px;
nDomstyledisplay = block;
documentgetElementsByTagName(body)[]appendChild(nDom);
var wh = get(nDom);
nDomparentNoderemoveChild(nDom);
return wh;
}
return get(dom);
}
//test
consolelog(getWH(documentgetElementById(content)));
var  domA = documentcreateElement("a") _ostyle =  "position:absolute;zindex:;width:px;height:px;position:absolute;display:none;";  
domAsetAttribute("style" _ostyle);
domAstylecssText = _ostyle;
domAsetAttribute("href" "javascript:void();");
documentgetElementsByTagName(body)[]appendChild(o);
consolelog(getWH(domA));
function getCss(elem css){
if (windowgetComputedStyle) {
return windowgetComputedStyle(elem null)[css];
}else if (elemcurrentStyle) {
return elemcurrentStyle[css];
}else {
return elemstyle[css];
}
}
function getWH(dom){
var get = function(elem){
var wh = {};
Width Heightreplace(/[^ ]+/g function(i){
var a = itoLowerCase();
wh[a] = elem[offset + i] || elem[client + i];
});
return wh;
};
if (getCss(dom display) === none) {
var nDom = domcloneNode(true);
nDomstyleposition = absolute;
nDomstyletop = px;
nDomstyledisplay = block;
documentgetElementsByTagName(body)[]appendChild(nDom);
var wh = get(nDom);
nDomparentNoderemoveChild(nDom);
return wh;
}
return get(dom);
}
//test
consolelog(getWH(documentgetElementById(content)));
var  domA = documentcreateElement("a") _ostyle =  "position:absolute;zindex:;width:px;height:px;position:absolute;display:none;";
domAsetAttribute("style" _ostyle);
domAstylecssText = _ostyle;
domAsetAttribute("href" "javascript:void();");
documentgetElementsByTagName(body)[]appendChild(o);
consolelog(getWH(domA));


还有其他更好的方法欢迎提出来

               

上一篇:Javascript拓展String方法小结

下一篇:解析javascript 数组以及json元素的添加删除