为什么我不能将top和left设置为$(window).width()* number

时间:2013-05-16 09:30:18

标签: html css css3

在我的css文件中,我设置了

#background_layer0{
   width: $(window).width();
   height: $(window).height();
}

它有效。但是,正如我设置的那样

#background_layer0{
   top: $(window).width() * 0.5;
   left: $(window).height() * 0.6;
}

它无法正常工作。我看不出这两种属性之间有什么区别:
width , heighttop left。 请纠正我的错误并解释原因。另外,我希望你能给我一些参考阅读。

更新:我需要将网页部署到另一台设备,例如:手机。 如果我只使用百分比作为值,它可以工作吗?

3 个答案:

答案 0 :(得分:2)

使用单独的JavaScript文件或将其包含在脚本标记

$('#background_layer0').css('top', function() {
    return $(window).width() * 0.5;
});

$('#background_layer0').css('left', function() {
    return $(window).height() * 0.6;
});

答案 1 :(得分:2)

您可以简单地使用百分比:

#background_layer0{
width: 100%;
height: 100%;
}

#background_layer0{
top: 50%;
left: 60%;
}

答案 2 :(得分:0)

因此,在CSS中,您无法使用$(window).height()$(window).width(),您必须以百分比,像素等方式指定它(它必须是绝对的)

要使对象的宽度与窗口宽度和高度相同,必须使用javascript / jquery