using .height()

using .height()

本文关键字:height using      更新时间:2023-09-26

我正在使用jquery .height()来获取文档高度。

请检查此http://jsfiddle.net/rkumarnirmal/86q37/

获取高度后,我将元素放置在该位置。您可以看到文档高度的位置实际上是错误的,因为它超出了该区域。

我该如何解决这个问题?

谢谢!

top相对于 #dummy 的顶部。

因此,您需要从页面高度中减去 #dummy 的高度:

$(function(){
    var h = $(document).height() - $("#dummy").height();
    $("#dummy").css("top", h+"px");
})​

我应该提到,你可以在纯CSS中做到这一点:

http://jsfiddle.net/86q37/3/

如果你想支持旧的浏览器,你要么需要查找一些CSS技巧来做到这一点,要么只是坚持使用JS。

.height返回正确的值。但是您将框的顶部位置设置为文档的高度。请参阅下面的演示以更好地理解,

$(function(){
    var h = $(document).height();
    $("#dummy").css("top", function () {
        return (h - $(this).height()) +"px"; 
      //This will place the box at top position subtracting 
      //the documentHeight - dummyHeight;
    });
})

演示

一种解决方案是使用 jQuery,并从主体的高度中减去元素的高度(并且你不需要担心将px添加到高度,jQuery 在内部处理它):

$(function(){
    var h = $(document).height();
    $("#dummy").css("top", h - $('#dummy').height());
})​

JS小提琴演示。

更简单的解决方案是简单地使用 CSS:

#dummy {
    position: absolute;            
    width: 100px;
    height: 100px;
    bottom: 0; /* aligns the bottom of the element zero pixels from the bottom of the document */
    left: 0; /* aligns the left side of the element zero pixels from the left side of the document */
    background-color: red;
}​

JS小提琴演示。