将css宽度字符串转换为常规数字 [英] Convert css width string to regular number

查看:769
本文介绍了将css宽度字符串转换为常规数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试计算隐藏元素的宽度时,我发现jquery.width()对于元素的宽度返回0。



我发现使用jquery.css('width')将通过使用声明的样式宽度返回正确的宽度(即使该值与初始样式表不同) )。问题是css('width')方法返回一个字符串,通常是100px的方式。我的问题解决:如何从100px字符串检索数字?

如果它总是以px格式返回,100px,50px (即不是em或百分比),你可以...

  var width = parseInt($ myelem)。css(width),10); //总是使用一个基数

虽然深度我认为有些是不正确的如果$ (#myelem)。width()无效。



注意隐藏元素。



如果您要添加jQuery以逐步增强页面,则您计算的元素在页面首次加载时应该可见。所以你应该在你最初隐藏元素之前获取宽度。通过这样做,$(#myelem)。width()将工作。

  var myWidth = 

$(document).ready(function(){
myWidth = $(#myelem)。width();
$(#myelem)。 ();
});


While trying to compute the width of an hidden element I found that jquery.width() returns 0 for that elements' width.

I found out that using jquery.css('width') would return the correct width by using the declared style width (even if that value is different from the initial stylesheet). The problem is that the css('width') method returns a string, generally in a "100px" fashion. My question resolves into: how to retrieve the number from the "100px" string? Is there an easy way?

解决方案

If it always returns in px format, "100px", "50px" etc (i.e. not "em" or percent), you could just...

var width = parseInt($("#myelem").css("width"),10); // always use a radix

Although deep down I'm thinking that something isn't right if $("#myelem").width() isn't working.

Note on hidden elements.

If you are adding jQuery to progressively enhance you page, the element you are calculating should be visible when the page first loads. So you should get the width before you initially hide the element. By doing this, $("#myelem").width() will work.

var myWidth = 0;

$(document).ready( function () {
    myWidth = $("#myelem").width();
    $("#myelem").hide();
});

这篇关于将css宽度字符串转换为常规数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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