【问题标题】:How can I persist state of slideToggle() in my case?在我的情况下,如何保持 slideToggle() 的状态?
【发布时间】:2017-10-10 05:18:52
【问题描述】:

我希望 javascript 函数 slideToggle() 保持它的状态。现在,每次我刷新页面时,它都会丢失信息。我知道可以使用 cookie 或 localstorage 来完成,但我没有这样做..

如果有人能告诉我如何在我的代码中实现解决方案,我将非常感激;

//toggle hide/show shout box
$(".close_btnn").click(function (e) {   
    //get CSS display state of .toggle_chat element
            var toggleState = $('.toggle_chat').css('display');
    //toggle show/hide chat box
    $('.toggle_chat').slideToggle();

    //use toggleState var to change close/open icon image
    if(toggleState == 'block')
    {
        $(".header div").attr('class', 'open_btnn');
    }else{
        $(".header div").attr('class', 'close_btnn');

    }


});

这是带有喊话框的页面的 HTML/PHP;

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--
.shout_box {
background: #000000;
width: 260px;
overflow: hidden;
position: fixed;
bottom: 0;
right: 10px;
z-index:9;
}
.shout_box .header .close_btn {
background: url(close_btn.gif) no-repeat 0px 0px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .close_btn:hover {
background: url(close_btn.gif) no-repeat 0px -16px;
}

.shout_box .header .open_btn {
background: url(close_btn.gif) no-repeat 0px -32px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .open_btn:hover {
background: url(close_btn.gif) no-repeat 0px -48px;
}
.shout_box .header{
padding: 5px 3px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: bold;
color:#fff;
border: 1px solid rgba(0, 39, 121, .76);
border-bottom:none;
cursor: pointer;
}
.shout_box .header:hover{
background-color: #000000;
}
.shout_box .message_box {
background: #FFFFFF;
height: 200px;
overflow:auto;
border: 1px solid #CCC;
}
.shout_msg{
margin-bottom: 10px;
display: block;
border-bottom: 1px solid #F3F3F3;
padding: 0px 5px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
color:#7C7C7C;
}
.message_box:last-child {
border-bottom:none;
}
time{
    font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: normal;
float:right;
color: #D5D5D5;
}
.shout_msg .username{
margin-bottom: 10px;
margin-top: 10px;
}
.user_info input {
width: 98%;
height: 25px;
border: 1px solid #CCC;
border-top: none;
padding: 3px 0px 0px 3px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.shout_msg .username{
font-weight: bold;
display: block;
}
-->
</style>

<script type="text/javascript" src="shoutbox/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
//window.setInterval(function(){
 $.post('shoutbox/shout.php', load_data,  function(data) {
    $('.message_box').html(data);
    var scrolltoh = $('.message_box')[0].scrollHeight;
    $('.message_box').scrollTop(scrolltoh);
 });
//}, 1000);

//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
    if(evt.which == 13) {
            var iusername = "java";
            var imessage = $('#shout_message').val();
            post_data = {'username':iusername, 'message':imessage};

            //send data to "shout.php" using jQuery $.post()
            $.post('shoutbox/shout.php', post_data, function(data) {

                //append data into messagebox with jQuery fade effect!
                $(data).hide().appendTo('.message_box').fadeIn();

                //keep scrolled to bottom of chat!
                var scrolltoh = $('.message_box')[0].scrollHeight;
                $('.message_box').scrollTop(scrolltoh);

                //reset value of message box
                $('#shout_message').val('');

            }).fail(function(err) { 

            //alert HTTP server error
            alert(err.statusText); 
            });
        }
});

//toggle hide/show shout box
$(".close_btn").click(function (e) {
    //get CSS display state of .toggle_chat element
    var toggleState = $('.toggle_chat').css('display');

    //toggle show/hide chat box
    $('.toggle_chat').slideToggle();

    //use toggleState var to change close/open icon image
    if(toggleState == 'block')
    {
        $(".header div").attr('class', 'open_btn');
    }else{
        $(".header div").attr('class', 'close_btn');
    }


});
});

</script>
</head>

<body>
<div class="shout_box">
<div class="header">Shout Box <div class="close_btn">&nbsp;</div></div>
  <div class="toggle_chat">
  <div class="message_box">
    </div>
    <div class="user_info">

   <input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" /> 
    </div>
    </div>
</div>
</body>
</html>

【问题讨论】:

  • 您能解释一下持久状态是什么意思吗?即使在浏览器刷新后你想保持聊天框打开吗?你能提供你的javascript的html吗?必须满足某些条件才能保持状态持久化,您的项目中有什么?
  • 我的意思是,每当我刷新页面时,默认情况下聊天框总是打开的。我希望如果用户关闭它,它会在用户打开网站时保持关闭状态..(我编辑了上一篇文章以向您展示页面的完整 html)

标签: javascript slidetoggle


【解决方案1】:

下面是使用localstorage 的方法。

$(document).ready(function() {
var $shoutBox = $('#shout-box');
var isShoutBoxClosed = JSON.parse(localStorage.getItem('shoutBoxClosed'));
if(isShoutBoxClosed){
	$shoutBox.hide();
}	
//toggle hide/show shout box
$(".close_btn").click(function (e) {
	//save users preference on localstoage
	localStorage.setItem('shoutBoxClosed', true);
    //toggle show/hide chat box
  $shoutBox.slideToggle();

});
	
});
.shout_box {
background: #000000;
width: 260px;
overflow: hidden;
position: fixed;
bottom: 0;
right: 10px;
z-index:9;
}
.shout_box .header .close_btn {
background: url(close_btn.gif) no-repeat 0px 0px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .close_btn:hover {
background: url(close_btn.gif) no-repeat 0px -16px;
}

.shout_box .header .open_btn {
background: url(close_btn.gif) no-repeat 0px -32px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .open_btn:hover {
background: url(close_btn.gif) no-repeat 0px -48px;
}
.shout_box .header{
padding: 5px 3px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: bold;
color:#fff;
border: 1px solid rgba(0, 39, 121, .76);
border-bottom:none;
cursor: pointer;
}
.shout_box .header:hover{
background-color: #000000;
}
.shout_box .message_box {
background: #FFFFFF;
height: 200px;
overflow:auto;
border: 1px solid #CCC;
}
.shout_msg{
margin-bottom: 10px;
display: block;
border-bottom: 1px solid #F3F3F3;
padding: 0px 5px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
color:#7C7C7C;
}
.message_box:last-child {
border-bottom:none;
}
time{
    font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: normal;
float:right;
color: #D5D5D5;
}
.shout_msg .username{
margin-bottom: 10px;
margin-top: 10px;
}
.user_info input {
width: 98%;
height: 25px;
border: 1px solid #CCC;
border-top: none;
padding: 3px 0px 0px 3px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.shout_msg .username{
font-weight: bold;
display: block;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<div id="shout-box" class="shout_box">
<div class="header">Shout Box <div class="close_btn">X</div></div>
  <div class="toggle_chat">
  <div class="message_box">
    </div>
    <div class="user_info">

   <input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" /> 
    </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>	
</body>
</html>

这里是上面sn -p https://jsbin.com/hewataz/edit?html,js,output的一个jsbin

【讨论】:

    【解决方案2】:

    正如您所指出的,您可以使用 cookie 来保存用户偏好。你可以阅读更多关于cookies

    当用户单击按钮切换聊天时,您会将 cookie 设置为该偏好。然后当页面加载时,您将读取 cookie 并在聊天框上设置 css。这是一个例子和一个工作小提琴

    https://fiddle.jshell.net/75nrozxd/1

    <div class="shout_box">
      <div class="header">Shout Box
        <div class="close_btn">Toggle</div>
      </div>
      <div class="toggle_chat">
        <div class="message_box">
        </div>
        <div class="user_info">
          <input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" />
        </div>
      </div>
    </div>
    
    <script>
    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)chatCSS\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    console.log("Cookie Value is: " + cookieValue)
    $('.toggle_chat').css("display", cookieValue);
    
    //toggle hide/show shout box
    $(".close_btn").click(function(e) {
      //get CSS display state of .toggle_chat element
      //toggle show/hide chat box
      $('.toggle_chat').slideToggle(function() {
        var toggleState = $('.toggle_chat').css('display');
        document.cookie = "chatCSS=" + toggleState;
        //use toggleState var to change close/open icon image
        if (toggleState == 'block') {
          $(".header div").attr('class', 'open_btn');
        } else {
          $(".header div").attr('class', 'close_btn');
        }
      });
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多