2

我在这里实现了一个粘性标题。

然而,当它到达它的粘点时,文本会向下移动,从容器中移出。

我想让它粘在容器里。

我的 HTML 和 Jq:

<div id="container">
<div id="menu">
    <ul>
        <li><a href='#'>Line 1</a></li>
        <li><a href='#'>Line 2</a></li>
        <li><a href='#'>Line 3</a></li>
    </ul>
</div>
</div>

我的脚本:

<script type="text/javascript">
    $(document).ready(function(){
        $(window).scroll(function(){
           if($(this).scrollTop()>=575)
           {
           $('#menu').addClass('fixed');
           }else{
               $('#menu').removeClass('fixed');
           }
                   });
    });
    </script>

CSS:

#menu{
    height: 35px;
    background-color:brown;
    z-index:200;
}

#menu ul li{
    float: left;
    list-style: none;
    line-height: 35px;
}

#menu a {
    color: #fff;
    text-decoration: none;
    font-size 16px;
    font-weight: bold;
    padding: 0 20px;
}

#menu.fixed{
    position: fixed;
    top:0;
    width: 720px;

}

#container{
    width: 720px;
    margin: 0 auto;
}

提前致谢

迈克尔

4

1 回答 1

1

这个元素转移是因为你的元素有默认边距。只需添加css

ul {
    margin:0;
}

但是,您最好在样式表的开头添加 css-reset,例如这个

 /**
 * Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)
 * http://cssreset.com
 */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

您应该使用 css 重置,因为所有浏览器都有默认的 css 规则,这可能会导致您的页面在不同浏览器之间呈现不同

于 2012-08-04T20:53:56.943 回答