使用javascript防止其他弹出窗口

prevent additional popups with javascript

本文关键字:窗口 其他 javascript 使用      更新时间:2023-09-26

我有一条提醒我的网站用户的消息:

alert("Message to users");

此消息显示在继承模板的每个页面上。

我想为用户创建一个选项,以停止使用javascript的额外警报消息。我想的是在消息下面打一个复选框,以停止其他消息。

下面是一个演示:http://jsfiddle.net/jR8hk/

每次运行它或重新加载页面时,一秒钟后都会出现一个警报。

但如果您选中该复选框,您将再也看不到该警报。它的工作原理是在本地计算机中使用localStorage设置一个首选项,正如我在评论中建议的那样。

以下是部分:

HTML:

<div id=alert>
    THIS IS A MESSAGE !
    <br><br><input type=checkbox id=alert_cb> SHUT UP
    <br><input type=button id=alert_close value = close>
</div>
<p>
    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal content    <br>normal conten    <br>normal contenttttttttttt
</p>

CSS:

#alert {
    display:none;
    background-color: red;
    z-index:2;
    position: fixed;
    left: 40px;
    right: 40px;
    top: 40px;
    height: 100px;
}​

JavaScript:

setTimeout(function(){
    if (!localStorage['stop_please']) $('#alert').show('slow'); 
}, 1000);

$('#alert_close').click(function(){
    if ($('#alert_cb').is(':checked')) localStorage['stop_please'] = "pleeeeaaaaase";
    $('#alert').hide();
});​

如果css不够漂亮,您可能需要对其进行调整。

Firefox在浏览器中内置了此功能。我想这就是你想要复制的功能?

这里有两个不同的问题。您是否在询问如何创建警报框,或如何存储设置?

如果你问如何创建警报框,有几种方法可以实现:

  1. 使用该选项创建您自己的自定义警报框
  2. 使用确认框而不是警报

选项1:看起来@dystroy提供了一个如何使用jQuery实现这一点的示例。

选项2:它将弹出一个确定/取消按钮。您可以将消息设置为类似以下内容:

"给用户的信息"

是否要阻止
这些弹出窗口从现在开始?

好的 nbsp nbsp nbsp 取消

如果他们点击OK,以某种方式存储设置,以防止弹出窗口再次发生。

或者,如果您希望用户能够在默认情况下单击"确定"而不阻止这些弹出窗口,您可以将消息更改为类似"按取消以阻止将来出现这些弹出窗口"的内容。

如果希望此设置在页面加载之间保持不变,则必须将其存储在数据库、cookie、会话变量或其他文件中。

你的代码可能看起来像这样:

if (/* check the setting to see if we should display a message */)
{
    var r = confirm("Message to users'n'nPress Cancel to prevent these popups in the future");
    if (!r)
    {
        // do something to store this setting
    }
}