YuC*_*YuC 44 javascript margin
我可以用jQuery获得高度
$(item).outerHeight(true);
Run Code Online (Sandbox Code Playgroud)
但是我如何使用JS?
我可以得到李的高度
document.getElementById(item).offsetHeight
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用margin-top时,我总会得到""
document.getElementById(item).style.marginTop
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 95
style
对象上的属性只是直接应用于元素的样式(例如,通过style
属性或代码).因此.style.marginTop
,如果您有专门分配给该元素的内容(未通过样式表分配等),则只会包含其中的内容.
要获取当前计算的对象样式,可以使用currentStyle
属性(Microsoft)或getComputedStyle
函数(几乎所有其他人).
例:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Run Code Online (Sandbox Code Playgroud)
公平警告:你得到的可能不是像素.例如,如果我p
在IE9中的元素上运行上面的操作,我会回来"1em"
.
GAU*_*SHI 11
这是我的解决方案:
第 1 步:选择元素
第 2 步:使用 getComputedStyle 并向其提供元素
第 3 步:现在访问所有属性
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
Run Code Online (Sandbox Code Playgroud)
它将为您提供px单位的边距,例如您可能不想要的“16px”。您可以使用提取值parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
Run Code Online (Sandbox Code Playgroud)
它只会给你数值(没有任何单位)。
当我在这个问题上寻找答案时,我在这个网站上发现了一些非常有用的东西.您可以在http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html上查看.帮助我的部分如下:
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
alert(marLeft);
/* and if a number needs to be in px... */
alert(marLeft + 'px');
////////////////////////////////////
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function (e, styleName) {
var styleValue = "";
if(document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
}
else if(e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以outerHeight
为HTML元素创建自己的.我不知道它是否适用于IE,但它适用于Chrome.也许,您可以使用currentStyle
上面的答案中提出的增强以下代码.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
Run Code Online (Sandbox Code Playgroud)
这段代码允许你做这样的事情:
document.getElementById('foo').outerHeight
Run Code Online (Sandbox Code Playgroud)
根据caniuse.com,主要浏览器(IE,Chrome,Firefox)支持getComputedStyle.