开发者

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

I've got a problem in internet explorer 6 and FF with something I'm trying to implement in jQuery. Basically there is an object at the top of the page using floated content that seems to be interfering with the $(window).scrollTop() property.

It was my understanding (and if I'm wrong, please help me by telling me the right way!) that $(window).scrollTop() would return the whitespace hidden by scrolling. I did some tests without the floated content and they seem to support this.

This is my code:

$(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();
        }
    });
});

This is the html document that shows the error (you just comment out the "evilFloatomoton" div below to see it working properly)

<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=开发者_C百科"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>

So instead of being against the top edge like I thought, it's halfway down the page in my tests. Can anyone help me?


For your scrollingDiv container, set the style to Position:absolute and top: 0px. That should keep your floating div in one spot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜