jQuery .css()函数不返回预期值 [英] jQuery .css() function not returning expected values

查看:106
本文介绍了jQuery .css()函数不返回预期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我搜索jQuery文档(需要有人专门维护),我搜索了SO,我搜索过Google。我找不到此问题的答案。

Alright, I've search the jQuery docs (needs somebody devoted to maintaining), I've searched SO, and I've searched Google. I can't find the answer to this question.

过去,我记得jQuery的工作方式如下:

In the past, I remember jQuery working like this:

$('#myObj')。 c $ c>返回 #myObj 的计算宽度。

$('#myObj')。css ')返回在CSS样式表中输入的宽度。

$('#myObj').width() returns the computed width of #myObj.
$('#myObj').css('width') returns the width as it is entered into the CSS stylesheet.

现在,任何使用的jQuery包都返回完全相同的数字

Now, any jQuery package I use returns the exact same number no matter which method I use.

$('#myObj')。width() code> #myObj 作为整数(float?)。

$('#myObj')。css('width')返回 #myObj 的计算宽度为 px p>




在Pseudocode中



$('#myObj').width() returns the computed width of #myObj as an integer (float?).
$('#myObj').css('width') returns the computed width of #myObj as a string with px on the end.

#myobject{
    width: 14em;
    height: 14em;
}

<div id="myobject">Has Text</div>

<script type="text/javascript">
    $( '#myobject' ).click(function(){
        alert($(this).css('width') + "\n" + $(this).width());
    });
</script>

//Always alerts "224px [newline] 224"
//Expected to alert "14em [newline] 224"






这些基于像素的返回值几乎完全无用,因为我需要根据CSS中的实际情况进行计算。例如,我想对一个元素的 left 位置进行数学运算,但我不能,因为它保持返回的像素值,这在<$ c $


These pixel-based return values are almost completely useless, as I need to do calculations based on what's actually in the CSS. For example, I want to do math on the left position of an element, but I can't because it keeps returning pixel values, which are worthless in an em-based design.

有没有办法在jQuery中获取CSS中的实际值?

这是一个jQuery错误,还是我缺少一些东西?

Is there any way to get the actual values out of the CSS in jQuery?
Is this a jQuery bug, or am I missing something?

这里是一个jsfiddle: http://jsfiddle.net/yAnFL/1/

Here's a jsfiddle: http://jsfiddle.net/yAnFL/1/.

显然,这是预期的结果。

我决定使用此插件为我执行转换。

删除CSS控件似乎在jQuery设计中是一个糟糕的选择。

Apparently, this is the intended result.
I have decided to use this plugin to do conversions for me.
Taking away control of CSS seems like a poor choice in the jQuery design.

推荐答案

这不是你的问题的完整答案,但它可能是一个工作的解决方案来计算em值。我从此处调整了此功能。和这里是更新的小提琴。

This is not a complete answer to your question but it may be a working solution to caclulate the em values. I adapted this function from here. And here is the updated fiddle.

$.fn.emWidth = function(){
    var wpx = this.width();
    var temp = $('<div />').css({
        width:'1em', 
        position: 'absolute'
    });
    this.append(temp);
    var oneEm = temp.width();
    temp.remove();
    var value = wpx/oneEm;
    return Math.round(value*100)/100;
};

这篇关于jQuery .css()函数不返回预期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆