dongyanhu5628
dongyanhu5628
2017-01-02 22:52

在重新加载页面上保持jquery打开之前隐藏的div

I have two divs. One acts as a chat window launcher. Chat window element is hidden by default. When I click the chat window launcher element, chat window appears and launcher hides. I've also made a small close button for the chat window that reverses the operation.

The problem is that when I reload the page, the chat window disappears and I have to relaunch again. What can I do, so that once the launcher is activated, the chat window remains visible even on page reload so that I can only close it using its close button?

HTML

<div class="chat-launcher" title="Launch Chat Window">
    <span class=" glyphicon glyphicon-pencil chat-launcher-pencil " style="color: #ffffff;font-size: 20px;"></span>
</div>
<div class="chat-window ">
    <span id="close">X</span>
</div>

jQuery

<script type="text/javascript">
    $(document).ready(function () {
        $('.chat-launcher').on('click', function () {
            $('.chat-window').show();
            $('.chat-launcher').hide();
        });
    });

    $(document).ready(function(){
        $('#close').on('click',function(){
            $('.chat-window').hide();
            $('.chat-launcher').show();
        });
    });
</script>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanbi3151 duanbi3151 4年前

    You need a persistent storage in order to save the chat window's state; like server-side sessions, client-side cookies or localStorage.

    Utilizing localStorage, it will be something along the lines of:

    $(document).ready(function () {
        $('.chat-launcher').on('click', function () {
            $('.chat-window').show();
            $('.chat-launcher').hide();
    
            // Set a flag indicating that the char window is open
            localStorage.setItem('chatWindowOpen', true);
        });
    
        $('#close').on('click',function(){
            $('.chat-window').hide();
            $('.chat-launcher').show();
    
            // Remove the flag
            localStorage.removeItem('chatWindowOpen');
        });
    
        // Open chat window if the flag is there
        if (localStorage.getItem('chatWindowOpen')) {
            $('.chat-launcher').trigger('click');    
        }        
    });
    

    One other note; As you might have noticed, you don't need multiple $(document).ready() calls. One will do for all.

    点赞 评论 复制链接分享