我有一个带有自动边距的 div,位于中心(水平)。
我想用 jQuery 检查 div 是否有边距自动。
我试图通过 .css()
获取左边距。 Mozilla Firefox 显示 0px,而 Chrome 显示一些像素...所以用这种方法我无法检查 div 是否有边距自动...
我尝试过的:
$( document ).ready(function() {
$("#the_margin").append( $("#example").css("margin-left") );
});
// Check with Chrome and Firefox...
// Firefox returns 0px, but Chrome returns a number of pixels
#example {
margin: 0 auto 0;
width: 300px;
border: 1px solid #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
Some Content
</div>
<div id="the_margin" style="font-weight: bold;">
The left margin is:
</div>
我能做什么? 非常感谢!
编辑
更清楚:如何在 JQUERY 中检查 DIV 是否有边距自动?
最佳答案
创建了一个函数,它读取 css 并检查指定的 id 是否有 margin 和 auto。
JS (JQuery)
function check_center( the_id ) {
var result = "";
var sheets = document.styleSheets;
var attribute_style = $(the_id).attr( "style" );
if(attribute_style.match(/margin:([a-z0-9- ]+?)auto/) || attribute_style.match(/margin:auto/) || (attribute_style.match(/margin-left:auto/) && attribute_style.match(/margin-right:auto/)) || (attribute_style.match(/margin-left: auto/) && attribute_style.match(/margin-right: auto/)) ) {
result = "true";
} else {
the_id.matches = the_id.matches || the_id.webkitMatchesSelector || the_id.mozMatchesSelector || the_id.msMatchesSelector || the_id.oMatchesSelector;
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (the_id.matches(rules[r].selectorText)) {
if(result != "true") {
if(rules[r].cssText.match(/margin:([a-z0-9- ]+?)auto/) || rules[r].cssText.match(/margin:auto/) || (rules[r].cssText.match(/margin-left:auto/) && rules[r].cssText.match(/margin-right:auto/)) || (rules[r].cssText.match(/margin-left: auto/) && rules[r].cssText.match(/margin-right: auto/)) ) {
result = "true";
} else {
result = "false";
}
}
}
}
}
}
if(result == "") {
result = "false";
}
return result;
}
$( document ).ready(function() {
$("#the_margin").append( check_center(document.getElementById('example')) );
});
HTML
<div id="example" style="width: 300px;">
Some Content
</div>
<div id="the_margin" style="font-weight: bold;">
The div is centered?
</div>
CSS
#example {
margin: 0 auto 0;
border: 1px solid #CCC;
}
fiddle http://jsfiddle.net/vn6ajt6r/6/
适用于:
- 外部样式表
- 内部样式表
- 内联样式
关于javascript - 检查 div 是否有 margin auto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321572/