jQuery和css函数的准确性
jQuery and the accuracy of the css function
可能重复:
jQuery和margin:0自动
我有以下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>
感谢你提出这个问题,在解决这个问题的过程中学到了很多
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jquery点击函数select&取消选择
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- Node.js v6.2.0类扩展不是函数错误
- 比较从函数和生成的日期对象
- jQuery中是否内置了任何字符串格式化函数
- jQuery和css函数的准确性