使用.css()和像素值设置left,top,width和height参数有效,但使用百分比值不行?

ben*_*ben 3 html css jquery

这个jQuery中,我正在画布div上画一个正方形:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: 1, top: 1,
                       width: 50, height: 50});        
});
Run Code Online (Sandbox Code Playgroud)

这很好用.但是我需要为left,top,width和height参数使用百分比而不是px值.我试过这个,但它不起作用:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: 1%, top: 1%,
                       width: 50%, height: 50%});        
});
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?谢谢阅读.

Nat*_*nes 7

他们需要成为字符串:'1%'不仅仅是1%.Javascript无法自行理解%符号.

所以:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: '1%', top: '1%',
                       width: '50%', height: '50%'});        
});
Run Code Online (Sandbox Code Playgroud)