日期:2014-05-16  浏览次数:20261 次

如何获取不带单位的像素值
如题,去样式中的长度,都是带了单位的,如何只获取数字(因为要计算)。
例如:$(#test).css("top"), 取出来时20px,如何得到数字20.

Canvas元素,为什么只有left与top有用,right与bottom无效的(position:absolute;),与它有独立的width与height属性由关?那如果一个canvas设了left与top,如何让它等同于bottom:0;right:0;

------解决方案--------------------
var left = $("#test").offset().left;
var top = $("#test").offset().top;
var width = $("#test").width();
var height = $("#test").height();

这些都是可计算的
------解决方案--------------------
1.有parseInt来转换
2. left、right 最好不要同时出现,top bottom 同理
如:
HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>    
        <style>
            div {
                position:absolute;
                left:100px; right:0;
                top:100px; bottom:0;
                width:100px; height:100px;
                border:1px solid red;
            }
        </style>        
    </head>
    <body>
        <div id="test"></div>
    </body>
</html>

------解决方案--------------------
探讨Canvas元素,为什么只有left与top有用,right与bottom无效的(position:absolute;),与它有独立的width与height属性由关?

------解决方案--------------------
HTML code
<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <script src="jquery.js"></script>
    <style>
        div{
            border: 1px solid black;
            width: 600px;
            height: 400px;
            position: relative;
        }
        canvas{
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <div>
        <canvas width="300" height="200"></canvas>
    </div>
    <p>dasfjasdflkasjdf</p>
    <script>
        var canvas = $('canvas');
        canvas.css({
            position: "absolute",
            right: "20px",
            bottom: "10px"
        });
        
        var pos = canvas.position();
        alert(pos.left);    // 278=600-300-20-1*2
        alert(pos.top);        // 188=400-200-10-1*2
        alert(canvas.css("left"))    // auto
        alert(canvas.css("top"))    // auto
        alert(canvas.css("right"))    // 20px
        alert(canvas.css("bottom"))    // 10px
    </script>
</body>
</html>