2017-07-19 27 views
0

我有一个包含jQuery的网站。当网站加载时,我正在检查cookie以查看用户是否已经接受cookie策略。如果用户以前没有接受过Cookie政策,我想在屏幕顶部向他们显示提示。我想推下其余的内容。出于这个原因,我想这推下身体

$(document).ready(function() { 
 
    var isAccepted = false; 
 
    if (isAccepted !== 'true') { 
 
    var notice = '<div><div id="myNotice" class="container" style="height:0px;">' + 
 
     'This site uses cookies. ' + 
 
     'Are you ok with this?' + 
 
     '<button id="acceptButton" class="btn btn-secondary">Accept</button>' + 
 
     '</div></div>'; 
 

 
    $('body').prepend(notice); 
 
    $('#myNotice').animate({ 
 
     height: 100 
 
    }, 200); 
 

 
    $('#acceptButton').on('click', function() { 
 
     $('#cookieNotice').animate({ 
 
     height: 0 
 
     }, 300); 
 
    }); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <h1> 
 
    Hello 
 
    </h1> 
 
</div>

我的问题是,该通知显示在顶部不管。它不会滑落,在页面加载时向下推“Hello”。我不知道为什么。我错过了什么?

+0

您的代码段工作正常。你的页面上是否有额外的CSS(例如固定位置标题)? –

+0

您的代码首先将'isAccepted'设置为'false',然后立即对* string *'true'进行测试。它会一直是'false',因为你在前一行将它设置为'false'。您需要测试cookie并根据您找到的内容设置“isAccepted”。 –

+1

此外,'isAccepted!=='true''实际上就是'!isAccepted' –

回答

0

首先你的病情不工作,只使用

if(!isAccepted){ 

因为说HERE,则!=====操作比较值和类型。你试图比较一个字符串和一个布尔值,所以它绝对不能工作。

此外,您必须将#cookieNotice更改为#myNotice,因为#cookieNotice不存在,所以您的按钮永远不会隐藏通知。

在我的片段,我改变了你生成通知DIV height = 0px;的风格display: none;并使用现有的jQuery .slideDown.slideUp,使您的通知幻灯片,你想同时给一个更好的可读性(在我看来)。

下面是完整的代码:

$(document).ready(function() { 
 
     var isAccepted = false; 
 
     if (!isAccepted) { 
 
      var notice = '<div><div id="myNotice" class="container" style="display: none;">' + 
 
       'This site uses cookies. ' + 
 
       'Are you ok with this?' + 
 
       '<button id="acceptButton" class="btn btn-secondary">Accept</button>' + 
 
       '</div></div>' 
 
      ; 
 
    
 
      $('body').prepend(notice); 
 
      $('#myNotice').slideDown(200); 
 
    
 
      $('#acceptButton').on('click', function() { 
 
       $('#myNotice').slideUp(300); 
 
      }); 
 
     } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 

 
    <h1> 
 
    Hello 
 
    </h1> 
 
</div>

0

试试这个时候它的接受效果基本show通知。

$(document).on('click', '#acceptButton', function() { 
    $('#myNotice').animate({ 
    height: 0 
    }, 300); 
});