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

标签 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>

最佳答案

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

我根据你的html和js来展示demo。现在看起来像您的网站:)

查看:http://jsfiddle.net/FrFsP/1/

关于javascript - jQuery如何计算实际屏幕距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18329413/

相关文章:

javascript - 如何在不知道宽度的情况下居中对齐 div?

javascript - 是否可以选择溢出特定 div 的所有元素并给它一些 CSS 并放置在另一个 div 中

html - 垂直对齐不是像素完美的

javascript - 多个页面的 HTML 页面模板

javascript - Javascript-这是什么类型的HTML表格,您可以使用哪种类型的网络抓取技术?

尽管在其中存储了值,但输出中的 javascript websql 代码值未定义

javascript - JS - 来自图像文件的 Canvas - 仅适用于存在浏览器缓存的情况

php - 如果输入为空并且输入不是现有的 Twitter 帐户,如何停止我的 javascript 运行?

javascript - JSON 解析在解析字符串时偶尔会出错

javascript - 检查json中是否存在某个元素