每个访问者显示一次jQuery弹出窗口

时间:2011-02-08 02:52:06

标签: jquery popup

如果此人是网站的新访问者,我该如何才能运行此脚本?它在每次请求页面时运行,这变得非常烦人。

//0 means disabled; 1 means enabled;
var popupStatus = 0;

function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#popupContact").fadeIn("slow");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#popupContact").fadeOut("slow");
        popupStatus = 0;
    }
}

//centering popup
function centerPopup(){
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupContact").height();
    var popupWidth = $("#popupContact").width();
    //centering
    $("#popupContact").css({
        "position": "absolute",
        "top": windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2
    });
    //only need force for IE6

    $("#backgroundPopup").css({
        "height": windowHeight
    });

}


$(document).ready(function(){

    //LOADING POPUP
    //Click the button event!
        //centering with css
        centerPopup();
        //load popup
        loadPopup();

    //CLOSING POPUP
    //Click the x event!
    $("#popupContactClose").click(function(){
        disablePopup();
    });
    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });

});

3 个答案:

答案 0 :(得分:4)

将Cookie设置为在会话结束时到期,值为1或true或其他。然后寻找cookie。如果存在,请不要显示它。

答案 1 :(得分:1)

如前所述,您需要在用户第一次看到该页面时创建一个Cookie,然后检查该Cookie是否存在于其他访问中。

创建Cookie的JavaScript并不是那么容易,因为您需要使用精确的格式设置字符串。使用这些helper functions that can be found on Quirksmode

更容易
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

然后在您的代码中,您需要做的就是:

if(readCookie("popupShown") == null) {
    // Create cookie for 30 days
    createCookie("popupShown", 1, 30);
    yourPopupFunction();
}

答案 2 :(得分:0)

Use cookies如果你想要一个纯粹的客户端方法。设置一个标记,表示用户已经看过您的介绍或其他内容。

如果网站具有某种身份验证,则可以由服务器处理。

上帝保佑你!