Possible Duplicate:
jQuery and margin: 0 auto
我有以下 HTML:
<p style="margin-left:auto; margin-right:auto; width:200px;">Hello</p>
然后我使用 jQuery 获取 margin-left
,如下所示:
alert(window.jQuery(element).css('margin-left'));
但是,它提醒 0px
而不是预期的 auto
。
为什么会这样,我怎样才能得到汽车?
找到解决办法了!这个小函数将采用 jQuery 选择器,扫描所有样式表,过滤影响给定 DOM 元素的规则,解析这些规则并返回一个对象,其中包含由所有相关继承交互产生的 CSS 规则列表。
<style type="text/css">
.fool{
margin-left:200px;
}
#fool{
margin-left:auto;
}
</style>
<div id="fool" class="fool" style="font-size:100px; height:20px;"></div>
<script type="text/javascript">
jQuery('document').ready(function($){
function get_inheritance_result(jQueryElement){
var styleSheets = document.styleSheets, finalRules = {};
for(var i in styleSheets) {
var rules = styleSheets[i].rules || styleSheets[i].cssRules;
for(var r in rules) {
var selector = String(rules[r].selectorText);
if(selector.indexOf(':') == -1){ //ignoring pseudo selectors, they will not matter here
if(jQueryElement.is(selector.toString())) {
console.log(selector.toString()); // Will log all the selectors that are affecting the particular DOM element
finalRules = $.extend(finalRules, rules[r].style);
}
}
}
}
//taking any inline css and overriding it on top of our finalRules variable:
var inlineCSS = jQueryElement.prop('style');
for(i in inlineCSS){
if(inlineCSS.hasOwnProperty(i)){
if(inlineCSS[i] != ""){
finalRules[i] = inlineCSS[i];
}
}
}
//and voila!
return finalRules;
}
var style = get_inheritance_result($("#fool"));
console.log(style); //logs all the resulted css rules
alert(style.marginLeft); // 'auto'!
alert(style.fontSize); // '100px'!
});
</script>
感谢您提出这个问题,在尝试解决该问题时学到了很多东西。