如何计算jQuery的实际屏幕距离?

时间:2013-08-20 07:35:49

标签: javascript jquery html

我想在页面栏中放置广告。当我向下滚动时,我希望广告一直跟随,但是位于页面的垂直中间。现在使用脚本只能设置一定距离但不能设置精确的50%距离。

我已经累了$window.height()/2$document.height()/2,但是他们会计算我的桌子高度而不是实际的屏幕高度。怎么解决这个?谢谢!

<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type="text/javascript">
$(function () {

var $sidebar = $("#sidebar"),
    $window = $(window);

$window.scroll(function () {
    if ($window.scrollTop() > $window.height() / 2) {

        $sidebar.css('position', 'absolute');
        $sidebar.css('top', $window.scrollTop() + $window.height() / 2);
        $sidebar.slideDown(500);
    } else {
        $sidebar.css('position', 'auto');
        $sidebar.css('top', 'auto');
    }
});

});
</script>
</head>

<body>

<br><br>
<table bgcolor="#CCCCCC" width="800" height="3000" align="center" border="1">
<tr>
<td width="150" valign="top">
<div style="width:100px;height:100;background:white;"></div>
<br>
<div style="width:100px;height:100;background:blue;"></div>
<br>
<div style="width:100px;height:100;background:yellow;"></div>
<br>
<div style="width:100px;height:100;background:pink;"></div>
<br>
<div style="width:100px;height:100;background:maroon;"></div>
<br>
<!-- AD -->
<div style="width:100px;height:100;background:red;" id="sidebar">test</div>

<br>

</td>
<td width="500"></td>
<td width="150"></td>
</tr>
</table>

</body>
</html>

5 个答案:

答案 0 :(得分:1)

尝试screen.height获取实际身高。 Reference

答案 1 :(得分:1)

从jquery文档中,$(window).height();应该返回浏览器视口的高度。

我根据你的html和js代表演示。它现在看起来像你的网站:)

看到它:http://jsfiddle.net/FrFsP/1/

答案 2 :(得分:0)

您需要window.innerHeight才能获得真实尺寸(适用于现代浏览器)。看一下JavaScript - Get Browser Height的小包装函数。

答案 3 :(得分:0)

如果我的想法正确,我认为this is what you are looking for 只需查看this example,看看是不是

如果不是您想要的,请您澄清一下吗?

答案 4 :(得分:0)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

如此处所述:http://api.jquery.com/height/

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return this;
}
$("div.target:nth-child(1)").center(true);
$("div.target:nth-child(2)").center(false);

JSFIDDLE DEMO