我需要用JavaScript獲取input
的margin-top
。這是jQuery代碼工作正常:用JavaScript獲取保證金頂部
alert($("#input").css('margin-top'))
但我需要它的純JavaScript,我都試過,沒有運氣
alert(document.getElementById('input').style.marginTop)
我怎樣才能使它在純JavaScript運行下面的代碼?
我需要用JavaScript獲取input
的margin-top
。這是jQuery代碼工作正常:用JavaScript獲取保證金頂部
alert($("#input").css('margin-top'))
但我需要它的純JavaScript,我都試過,沒有運氣
alert(document.getElementById('input').style.marginTop)
我怎樣才能使它在純JavaScript運行下面的代碼?
我只是找到了一個解決方案:
var style = window.getComputedStyle(document.getElementById('input'));
var marginTop = style.getPropertyValue('margin-top');
alert(marginTop);
不幸的是,它不會在IE 9中工作。在過去,我已經從jQuery源代碼中提取了方法'curCSS'來支持所有瀏覽器,但它並不漂亮:) – robC
這裏是jQuery的curCSS的獨立版本。請注意我爲了保持代碼大小而做的編輯。迄今爲止還沒有造成任何問題。
//Get current CSS - from jQuery-1.9.0
var curCSS;
(function(){
/*!
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*/
var getStyles, core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
rmargin = /^margin/, rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i");
if(window.getComputedStyle){
getStyles = function(elem){return window.getComputedStyle(elem, null)};
curCSS = function(elem, name, _computed){
var width, minWidth, maxWidth, computed = _computed || getStyles(elem),
ret = computed ? computed.getPropertyValue(name) || computed[ name ] : undefined,
style = elem.style;
if(computed){
/* Edit - removed edge case as requires lots more jQuery code
if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {ret = jQuery.style(elem, name)}*/
if(rnumnonpx.test(ret) && rmargin.test(name)){
width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret; ret = computed.width;
style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth}}
return ret;
}
}
else if (document.documentElement.currentStyle){
getStyles = function(elem){return elem.currentStyle};
curCSS = function(elem, name, _computed){
try{
var left, rs, rsLeft, computed = _computed || getStyles(elem),
ret = computed ? computed[ name ] : undefined, style = elem.style;
if(ret == null && style && style[ name ]) {ret = style[ name ]}
if(rnumnonpx.test(ret) && !rposition.test(name)) {
left = style.left; rs = elem.runtimeStyle;rsLeft = rs && rs.left;
if (rsLeft) {rs.left = elem.currentStyle.left}
style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px";
style.left = left; if (rsLeft) {rs.left = rsLeft}}
return ret === "" ? "auto" : ret
}
catch(e){};
}
}
})();
的[得到一個div的JavaScript邊距]
對於IE 8中的計算樣式非常有用!儘管你缺少一個變量:'rposition =/^(top | right | bottom | left)$ /;'。 – Beejor
可能重複(http://stackoverflow.com/questions/7078558/get-margins-from-a-div-javascript) –
@MarcelGwerder - 這是不。儘管這個問題的標題,它是關於*設置*沒有得到。 – Quentin
您確定文檔中只有一個id =「input」的元素嗎? – ricksuggs