繁体   English   中英

jQuery获得将元素放在屏幕顶部所需的页边距

[英]jQuery getting the margin-top needed to put element on the top of the screen

我在Internet Explorer 6和FF中遇到了我要在jQuery中实现的问题。 基本上,页面顶部有一个使用浮动内容的对象,似乎在干扰$(window).scrollTop()属性。

这是我的理解(如果我错了,请告诉我正确的方法来帮助我!)$(window).scrollTop()将返回通过滚动隐藏的空白。 我做了一些没有浮动内容的测试,他们似乎支持这一点。

这是我的代码:

$(document).ready(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() > 180) { //is the window scrolled enough to hide the header?
            var $myDiv = $("#scrollingDiv");
            if ($myDiv.is(":hidden")) { //if mydiv is currently hidden, show it
                $myDiv.show();
            }
            $myDiv.stop();
            $myDiv.animate({ marginTop: ($(window).scrollTop()) + "px" }, "fast", function() { /*animation complete*/ }); //move mydiv to the top edge of the page... OR SO I THOUGHT!
        }
        else { //otherwise hide it, since the header is visible
            $("#scrollingDiv").hide();
        }
    });
});

这是显示错误的html文档(您只需注释掉下面的“ evilFloatomoton” div即可看到其正常工作)

<HTML>
<HEAD>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() > 180) {
            var $myDiv = $("#scrollingDiv");
            if ($myDiv.is(":hidden")) {
                $myDiv.show();
                            }
            $myDiv.stop();
            $myDiv.animate({ marginTop: ($(window).scrollTop()) + "px" }, "fast", function() { /*animation complete*/ });
        }
        else {
            $("#scrollingDiv").hide();
        }
    });
});
</script>
<style type="text/css">
<!-- Enter any CSS to make objects viewable here -->
#scrollingDiv
{
    width: 100%;
    position: absolute;
    margin-top: 0px;
}
</style>
</HEAD>
<BODY>
<!-- Enter in test elements here -->
<div style="overflow: auto;">
    <div id="evilFloatomoton" style="float: left; height: 200px; width: 100%;">
        CONTENT<br /><br />
    </div>
</div>
<div id="scrollingDiv" style="background-color: #000; color: #FFF;">
    Scrolling floating div of doom
</div>
<div style="height: 180px; border: solid 1px #000;">
    *Highlight the 180 px scroll area*
</div>
<div style="height: 10000px;">

</div>
</BODY>
</HTML>

因此,它并没有像我想的那样靠在顶端,而是在测试的页面中间。 谁能帮我?

对于您的scrollingDiv容器,将样式设置为Position:absolute和top:0px。 那应该使您的浮动div集中在一个位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM