像Stack Overflow这样的介绍栏

时间:2010-04-09 10:36:40

标签: jquery javascript

我有一个简单的顶级栏使用jQuery,就像Stack Overflow上的那个,但我希望它只在第一次有人访问网站时出现。

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="bxSlider.js"></script>
        <title>topbar</title>

        <style type="text/css" media="screen">
            #message {
                font-family:Arial,Helvetica,sans-serif;
                position:fixed;
                top:0px;
                left:0px;
                width:100%;
                z-index:105;
                text-align:center;
                color:white;
                padding:2px 0px 2px 0px;
                background-color:#8E1609;
            }

            #example1 {
                text-align: center;
                width: 80%;
            }

            .close-notify {
                white-space: nowrap;
                float:right;
                margin-right:10px;
                color:#fff;
                text-decoration:none;

                padding-left:3px;
                padding-right:3px
            }

            .close-notify a {
                color: #fff;
            }

            h4, p {
                margin:0px;
                padding:0px;
            }
        </style>
    </head>

    <body>
        <DIV ID='message' style="display: none;">
            <DIV ID="example1">
                <DIV CLASS="item">
                    <h4>Head 1</h4>
                    <p>Text 1</p>
                </div><!-- end item -->

                <DIV CLASS="item">
                    <h4>Head 2</h4>
                    <p>Text 2</p>
                </div><!-- end item -->
            </div><!-- end example1 -->
            <a href="#" CLASS="close-notify" onclick="closeNotice()">X</a>
        </div>

        <script type="text/javascript">
            $(document).ready(function() {
             $("#message").fadeIn("slow");
             $('#example1').bxSlider({
              mode: 'slide',
              speed: 250,
              wrapper_CLASS: 'example1_container'
              });
            });

            function closeNotice() {
                $("#message").fadeOut("slow");
            }
        </script>
    </body>
</html>

bxSlider.js:

/**
*
*
* bxSlider: Content slider / fade / ticker using the jQuery javascript library.
*
* Author: Steven Wanderski
* Email: wandoledzep@gmail.com
* URL: http://bxslider.com
*
*
**/

jQuery.fn.bxSlider = function(options){

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Declare variables and functions
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var defaults = {
        mode: 'slide',
        speed: 500,
        auto: false,
        auto_direction: 'left',
        pause: 2500,
        controls: true,
        prev_text: 'prev',
        next_text: 'next',
        width: $(this).children().width(),
        prev_img: '',
        next_img: '',
        ticker_direction: 'left',
        wrapper_class: 'container'
    };

    options = $.extend(defaults, options);

    if(options.mode == 'ticker'){
        options.auto = true;
    }

    var $this = $(this);

    var $parent_width = options.width;
    var current = 0;
    var is_working = false;
    var child_count = $this.children().size();
    var i = 0;
    var j = 0;
    var k = 0;

    function animate_next(){
        is_working = true;
        $this.animate({'left':'-' + $parent_width * 2 + 'px'}, options.speed, function(){
            $this.css({'left':'-' + $parent_width + 'px'}).children(':first').appendTo($this);
            is_working = false;
        });
    }

    function animate_prev(){
        is_working = true;
        $this.animate({'left': 0}, options.speed, function(){
            $this.css({'left':'-' + $parent_width + 'px'}).children(':last').insertBefore($this.children(':first'));
            is_working = false;
        });
    }

    function fade(direction){
        if(direction == 'next'){
            var last_before_switch = child_count - 1;
            var start_over = 0;
            var incr = k + 1;
        }else if(direction == 'prev'){
            var last_before_switch = 0;
            var start_over = child_count -1;
            var incr = k - 1;
        }

        is_working = true;
        if(k == last_before_switch){
            $this.children().eq(k).fadeTo(options.speed, 0);
            $this.children().eq(start_over).fadeTo(options.speed, 1, function(){
                is_working = false;
                k = start_over;
            });

        }else{
            $this.children().eq(k).fadeTo(options.speed, 0);
            $this.children().eq(incr).fadeTo(options.speed, 1, function(){
                is_working = false;
                k = incr;
            });
        }
    }

    function add_controls(){
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Check if user selected images to use for next / prev
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(options.prev_img != '' || options.next_img != ''){
            $this.parent().append('<a class="slider_prev" href=""><img src="' + options.prev_img + '" alt=""/></a><a class="slider_next" href=""><img src="' + options.next_img + '" alt="" /></a>');
        }else{
            $this.parent().append('<a class="slider_prev" href="">' + options.prev_text + '</a><a class="slider_next" href="">' + options.next_text + '</a>');
        }

        $this.parent().find('.slider_prev').css({'float':'left', 'outline':'0', 'color':'yellow'});
        $this.parent().find('.slider_next').css({'float':'right', 'outline':'0', 'color':'yellow'});


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Accomodate padding-top for controls when elements are absolutely positioned (only in fade mode)
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(options.mode == 'fade'){
           $this.parent().find('.slider_prev').css({'paddingTop' : $this.children().height()})
           $this.parent().find('.slider_next').css({'paddingTop' : $this.children().height()})
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Actions when user clicks next / prev buttons
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        $this.parent().find('.slider_next').click(function(){
            if(!is_working){
                if(options.mode == 'slide'){
                    animate_next();
                    if(options.auto){
                        clearInterval($.t);
                        $.t = setInterval(function(){animate_next();}, options.pause);
                    }
                }else if(options.mode == 'fade'){
                    fade('next');
                    if(options.auto){
                        clearInterval($.t);
                        $.t = setInterval(function(){fade('next');}, options.pause);
                    }
                }
            }
            return false;
        });

        $this.parent().find('.slider_prev').click(function(){
            if(!is_working){
                if(options.mode == 'slide'){
                    animate_prev();
                    if(options.auto){
                        clearInterval($.t);
                        $.t = setInterval(function(){animate_prev();}, options.pause);
                    }
                }else if(options.mode == 'fade'){
                    fade('prev');
                    if(options.auto){
                        clearInterval($.t);
                        $.t = setInterval(function(){fade('prev');}, options.pause);
                    }
                }
            }
            return false;
        });
    }


    function ticker() {
        if(options.ticker_direction == 'left'){
            $this.animate({'left':'-' + $parent_width * 2 + 'px'}, options.speed, 'linear', function(){
                $this.css({'left':'-' + $parent_width + 'px'}).children(':first').appendTo($this);
                ticker();
            });
        }else if(options.ticker_direction == 'right'){
            $this.animate({'left': 0}, options.speed, 'linear', function(){
                $this.css({'left':'-' + $parent_width + 'px'}).children(':last').insertBefore($this.children(':first'));
                ticker();
            });
        }
    }


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Create content wrapper and set CSS
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    $this.wrap('<div class="' + options.wrapper_class + '"></div>');
    //console.log($this.parent().css('paddingTop'));
    if(options.mode == 'slide' || options.mode == 'ticker'){
        $this.parent().css({
            'overflow' : 'hidden',
            'position' : 'relative',
            'margin' : '0 auto',
            'width' : options.width + 'px'
        });

        $this.css({
            'width' : '999999px',
            'position' : 'relative',
            'left' : '-' + $parent_width + 'px'
        });

        $this.children().css({
            'float' : 'left',
            'width' : $parent_width
        });

        $this.children(':last').insertBefore($this.children(':first'));
    }else if(options.mode == 'fade'){
     $this.parent().css({
         'overflow' : 'hidden',
         'position' : 'relative',
         'width' : options.width + 'px'
         //'height' : $this.children().height()
     });

     if(!options.controls){
         $this.parent().css({'height' : $this.children().height()});
     }

     $this.children().css({
         'position' : 'absolute',
         'width' : $parent_width,
         'listStyle' : 'none',
         'opacity' : 0
     });

     $this.children(':first').css({
         'opacity' : 1
     });
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Check if user selected "auto"
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if(!options.auto){
        add_controls();
    }else{
        if(options.mode == 'ticker'){
            ticker();
        }else{
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Set a timed interval
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if(options.mode == 'slide'){
                if(options.auto_direction == 'left'){
                    $.t = setInterval(function(){animate_next();}, options.pause);
                }else if(options.auto_direction == 'right'){
                    $.t = setInterval(function(){animate_prev();}, options.pause);
                }
            }else if(options.mode == 'fade'){
                if(options.auto_direction == 'left'){
                    $.t = setInterval(function(){fade('next');}, options.pause);
                }else if(options.auto_direction == 'right'){
                    $.t = setInterval(function(){fade('prev');}, options.pause);
                }
            }
            if(options.controls){
                add_controls();
            }
        }
    }
}

4 个答案:

答案 0 :(得分:9)

你可以use JavaScript to set cookies

加载页面时,请检查Cookie。如果cookie存在,他们已经去过该网站。如果没有,他们就没有。这并不完美(您可以轻松删除cookie),但它确实有效。

然后,要么更改同一个cookie的值,要么设置一个新的cookie来说明用户是否点击了x。

我不想只复制和粘贴代码,但W3C schools example几乎正是您所需要的。

基本上你将有三种状态:

  • 从未来过这里(没有饼干)
  • 在这里但未点击x(cookie name =“new_user_status”,value =“new”或其他东西)
  • 点击x(cookie name =“new_user_status”,value =“他们很好”。或者其他)

您甚至可以为要显示的每条消息执行此操作。

  • cookie name = [无论你的留言标题是什么]
  • cookie value = show / hide

答案 1 :(得分:3)

Cookie是一个开始,但它们可以轻松清除,但可能无法启用。更强大的解决方案是使用其他形式的本地存储,如果没有cookie,则回退到cookie。您的其他一些选择是:

  • HTML5本地存储
  • Flash持久存储
  • IE本地存储
  • Google Gears
  • 缓存

如果某人还没有为你做这件事,那么实施这件事会很痛苦。如果您认为Cookie不够,请结帐Persist-Js。仅仅检测到一个新用户可能有点过分,但如果你对cookie不满意,那么这会为你提供更多的选择。

答案 2 :(得分:2)

您必须使用某种会话来存储用户已经显示一次条形图的值。另一种方法是使用cookie。一旦设置完毕,您可以检查是否设置了它,如果不是,则不显示该栏。

session_start();

if (!isset($_SESSION['bar_shown']))
{
   // show your info bar

   // finally set the session
   $_SESSION['bar_shown'] = true;
}

答案 3 :(得分:1)

所以我会说饼干是去这里而不是会话的方式。你的措辞略显含糊,但我想你只想在第一次访问网站时显示这个栏。

你正在使用jQuery所以我建议使用jQuery cookie插件来进行实际的cookie读写。在http://plugins.jquery.com/project/cookie获取。

用户点击栏上的x后,像以前一样调用关闭通知功能,但添加了一个Cookie集:

function closeNotice() {
    $("#message").fadeOut("slow");
    var date = new Date();
    //Here we set the expire time to 999 days worth of milliseconds
    date.setTime(date.getTime() + (999 * 24 * 60 * 60 * 1000));
    $.cookie("NO_BAR", 1, { path: '/', expires: date });
}

然后您的文档就绪功能变为

$(document).ready(function() {
   if (!$.cookie("NO_BAR")) {    
     $("#message").fadeIn("slow");
         $('#example1').bxSlider({
            mode: 'slide',
            speed: 250,
            wrapper_CLASS: 'example1_container'
         });
   }

});

如果我误解了你的问题并且你真的希望第一次在每次访问时显示该栏,那么你想要一个会话cookie。要做到这一点,只需将所有过期日期一起删除:

$.cookie("NO_BAR", 1, { path: '/'});
相关问题