jQuery css('left')报告为'px'而不是'%' [英] jQuery css('left') reports 'px' instead of '%'

查看:125
本文介绍了jQuery css('left')报告为'px'而不是'%'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

偶然发现了一个问题,我相信必须有一个简单的解释,由于某种原因,今天我仍然无法理解.

Just stumbled across a problem which I am sure must have a simple explanation that just eludes me today for some reason.

如果我想确定绝对位置带有precentage值的元素的CSS设置,则jQuery仅返回像素值( http://jsfiddle.net/xTUR3/2/):

If I want to determine the CSS setting for an element absolutely positioned with a precentage value, jQuery only returns the pixel value ( http://jsfiddle.net/xTUR3/2/):

HTML:

<div id="wrp">test</div>
<div id="out">$('wrp').css('left') = <span></span></div>

CSS:

#wrp {
   position: absolute;
   left: -150%;
   width: 200%;
   background-color: green;
   height: 50%;    
}

#out {
   position: absolute;
   top: 50%;    
}

JS:

$(document).ready(function() {
    var wrp = $('#wrp');
    $('#out span').html(wrp.css('left'));
});

任何人都知道是否有一种无需编写专用的px-to-%-conversion函数即可检索precentage值的方法吗?

Anyone got an idea whether there's a way retrieve the precentage value without writing a dedicated px-to-%-conversion function?

推荐答案

代码:

$(document).ready(function() {
    var lft = $('#wrp').css("left")+"";
    if (lft.match("px")) {
        lft = (lft.split("px").join("")*1/$('#wrp').parent().width())*100;
        if ($.browser == "msie")
            lft = lft>0 ? Math.ceil(lft) : Math.floor(lft);
        lft += "%";                     
    }
    $('#out span').html(lft);
});​

这篇关于jQuery css('left')报告为'px'而不是'%'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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