2013-02-03 224 views
-1

我想获得窗口的宽度&高度+ div的宽度&高度来找到调整的宽度。我也试图绝对定位div与jquery,但我的代码不起作用。我将提供下面的代码。jquery css选择器不工作

CSS:

#inner { 
    width: 500px; height: 300px; 
    background: #ff0000; 
} 

的jQuery:

$(document).ready(function() { 

    var screenWidth = $(window).width(); 
    var screenHeight = $(window).height(); 

    var boxWidth = $("#inner").width(); 
    var boxHeight = $("#inner").height(); 

    var adjustedWidth = screenWidth - boxWidth; 
    var adjustedHeight = screenHeight - boxHeight; 

    $("#inner").css('position', 'absolute'); 
    $("#inner").css('top', adjustedWidth + 'px'); 
    $("#inner").css('left', adjustedHeight + 'px'); 

}); 

我在做什么错在我的jQuery?希望我的解释清楚。

+2

“我的代码不工作”是什么意思?你有错误吗?你没有得到你期望的结果吗?你得到了什么,你期望什么?请创建一个http://jsfiddle.net/演示。 –

+0

您是否可以发布关联的HTML以防它在问题中起作用? –

+0

试过一个jsfiddle:http://jsfiddle.net/gnvaG/它似乎工作正常(检查结果的来源)。你可能没有正确包含jQuery,或者你的HTML不正确。 – jgthms

回答

1

如果你想在最底层右对齐的DIV,那么你已经混了顶 - > adjustedWidth和左 - > adjustedHeight:

$("#inner").css('top', adjustedWidth + 'px'); 
$("#inner").css('left', adjustedHeight + 'px'); 

当它应该是其他方式周围:

$("#inner").css('top', adjustedHeight + 'px'); 
$("#inner").css('left', adjustedWidth + 'px'); 

除此之外,您的代码looks like it works

此外,您在尝试更改CSS宽度或高度时不需要添加“px”。

0

没有必要为此使用JavaScript。当绝对定位的东西,lefttop不是唯一的东西,你可以使用;相反,您可以在适当的地方使用rightbottom。例如,你似乎是在做定位的东西在右下角,你可以这样做:

#something { 
    position: absolute; 
    right: 0; 
    bottom: 0; 
    width: 300px; 
    height: 150px; 
    background: red; 
} 

Try it.

0

如果代码包括得到一个组件的尺寸(尤其是有图像在页面上),您希望将代码放在load处理程序中,而不是ready处理程序,因为ready在下载所有图像之前执行,并且在此之后页面的大小可能会有所不同。

另外你的topleft应该交换。

$(document).on('load', function() { 

    var screenWidth = $(window).width(); 
    var screenHeight = $(window).height(); 

    var boxWidth = $("#inner").width(); 
    var boxHeight = $("#inner").height(); 

    var adjustedWidth = screenWidth - boxWidth; 
    var adjustedHeight = screenHeight - boxHeight; 

    $("#inner").css('position', 'absolute'); 
    $("#inner").css('top', adjustedHeight + 'px'); 
    $("#inner").css('left', adjustedWidth + 'px'); 

});