如题,去样式中的长度,都是带了单位的,如何只获取数字(因为要计算)。
例如:$(#test).css("top"), 取出来时20px,如何得到数字20.Canvas元素,为什么只有left与top有用,right与bottom无效的(position:absolute;),与它有独立的width与height属性由关?那如果一个canvas设了left与top,如何让它等同于bottom:0;right:0;

解决方案 »

  1.   

    var left = $("#test").offset().left;
    var top = $("#test").offset().top;
    var width = $("#test").width();
    var height = $("#test").height();这些都是可计算的
      

  2.   

    1.有parseInt来转换
    2. left、right 最好不要同时出现,top bottom 同理
    如:<!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>这里 right 和 bottom 被无视了,同时出现的话,left 比right 更优先?(没研究过)
      

  3.   

    位置的计算是根据  top与left来计算的,就像x y 轴  
    只不过远点在左上角 
    x往右数值变大
    y往下数值变大
      

  4.   


    貌似确实会被无视,刚试了下,
    console.log(__canvas[0].offsetTop);
            console.log(parseInt(__canvas.css("top")));
            console.log(__canvas.position().top);
    这些都可以取到实际的top值,而offset().top;取到的是全局的top值,不是相对于父元素的。不能用right,那就是能用父容器的width - left来得到canvas的width了,还有其它更简便的方法吗?
      

  5.   

    不明白你这句话什么意思,我测试了下完全没问题<!doctype html>
    <html>
    <head>
    <meta charset="utf-8"/>
    <style>
    div{
    border: 1px solid black;
    width: 600px;
    height: 400px;
    position: relative;
    }
    canvas{
    position: absolute;
    bottom: 0;
    right: 0;
    border: 1px solid black;
    }
    </style>
    </head><body>
    <div>
    <canvas width="300" width="200"></canvas>
    </div>
    <p>dasfjasdflkasjdf</p>
    </body>
    </html>
      

  6.   

    <!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>