使用.prepend if语句添加文本

时间:2015-07-23 18:46:28

标签: jquery html

我正在用jQuery创建一个响应式导航栏:
HTML:

<div class="head-wrap">
     <h1>Header Content</h1>

    <ul class="horiz-nav">
        <li><a href="#">Nav bar link</a>
        </li>
        <li><a href="#">Nav bar link</a>
        </li>
        <li><a href="#">Nav bar link</a>
        </li>
    </ul>
</div>

JS:

$(function(){
    $(document).scroll(function(){
        if($(this).scrollTop() > 90){
            var header = $(".horiz-nav");
            $(".horiz-nav").stop().css({'position' : 'fixed'}).animate({ 'top' : '0px'}, 0);
            header.prepend("<li>Header Content</li>");
        } else {
            $(".horiz-nav").stop().css('position', 'absolute').stop().animate({'top' : '38px'}, 100);
        }
    });

这主要适用于它:它会在用户滚动时使导航栏切换位置。但我想要做的是在页面滚动时使导航栏上方的h1成为导航栏的一部分。但是,当页面滚动时,此代码会生成h1(虽然更小)的数十个副本。如何在其他导航栏项目之前只显示一个? FIDDLE

2 个答案:

答案 0 :(得分:3)

仅在元素不存在时才前置

if(!$('#element').length) {...}

$(function(){
    $(document).scroll(function(){
        if($(this).scrollTop() > 90){
            var header = $(".horiz-nav");
            $(".horiz-nav").stop().css({'position' : 'fixed'}).animate({ 'top' : '0px'}, 0);
            if(!$('#added').length) {
              header.prepend("<li id='added'>Header Content</li>");
            }
        } else {
            $(".horiz-nav").stop().css('position', 'absolute').stop().animate({'top' : '38px'}, 100);
        }
    });

答案 1 :(得分:0)

您可以在$('.head-wrap > h1').prependTo(header);if中使用header.find('h1').prependTo('.head-wrap');。他们将只是第二次成功一次,那个元素将不再存在。

$(document).scroll(function () {
    var header = $(".horiz-nav");
    if ($(this).scrollTop() > 90) {

        $(".horiz-nav").stop().css({
            'position': 'fixed'
        }).animate({
            'top': '0px'
        }, 0);
        $('.head-wrap > h1').prependTo(header);
    } else {
        $(".horiz-nav").stop().css('position', 'absolute').stop().animate({
            'top': '38px'
        }, 100);
        header.find('h1').prependTo('.head-wrap');
    }
});

请参阅Fiddle