0

I have tried to make a div (id="hoe") that sticks to the top of the from the moment the user scrolls. before scrolling, the div is located under the header. Unfortunately, i can't get it to work after lot's of trying. Any tips and help on what I do wrong is greatly appreciated. Here is my code in a test version:

<!DOCTYPE html>
<head>

<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<style type="text/css">

#header
{
background-color: blue;
width: 100%;
height: 125px;
}

#hoe
{ 
background-color: red;
height: 180px;
width: 100%;
z-index: 9999;
top: 125;
position: fixed;
}

#een
{
margin-top: 180px;
background-color: green;
height: 700px;
width: 100%;
}

</style>

<script type="text/javascript">
$(document).ready(function() {

if ($('body').hasClass('lock')) {
    bar_pos = $('#hoe').offset();
    if (bar_pos.top >= (125+180)) {
        $('#hoe').css('top', 0);
        //document.getElementById("hoe").style.top="0"; also tried this
    }
});
});

</script>

</head>
<body class="lock">
<div id="header">
</div>
<div id="hoe">
</div>
<div id="een">
</div>
</body>
</html>
4

3 回答 3

3

我修改了你的代码并在这里创建了一个小提琴:http: //jsfiddle.net/UcX4A/

你的javascript中有一个多余的括号

$(document).ready(function() {
    if ($('body').hasClass('lock')) {
        bar_pos = $('#hoe').offset();
        if (bar_pos.top >= (125+180)) {
            $('#hoe').css('top', 0);
            //document.getElementById("hoe").style.top="0"; also tried this
        }
    }); <<< Surplus bracket
});

此外,“滚动”事件没有附加到任何东西,因此没有被评估。我改变了你的:

$(document).ready(function() {

一个:

$(window).scroll(function() {
于 2013-02-08T12:48:09.890 回答
1

看到这个:http: //jsfiddle.net/WTnEd/

使用$(window).scroll()

$(document).ready(function () {
var bar_pos;
$(window).scroll(function (e) {
    if ($('body').hasClass('lock')) {
        bar_pos = $('#hoe').offset();
        if (bar_pos.top >= (125 + 180)) {
            $('#hoe').css('top', 0);
        }
        else{
            $('#hoe').css('top', 125);
        }
    };
});
});
于 2013-02-08T12:52:36.153 回答
1

据我了解,这是开始滚动时将 div 粘贴到页面顶部的另一种方法:

<div id="header" style="position:fixed; top:0px; left:0px; right:0px;
    height:100px; z-index:2; background:blue;"></div>
<div id="hoe" style="position:fixed; top:100px; left:0px; right:0px;
    height:100px; z-index:2; background:red;"></div>
<div id="een" style="position:absolute; top:200px; left:0px; right:0px;
    height:100px; z-index:1;">
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
</div>
于 2013-02-09T13:20:58.603 回答