JavaScript侧边栏保持打开页面更改 [英] javascript sidebar stay open on page change

查看:253
本文介绍了JavaScript侧边栏保持打开页面更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击一个过滤器,内容也会根据这个和页面URL改变,所以侧边栏关闭。



我想要做的是侧边栏保持开放,直到用户点击X ..



我为此使用了W3School边栏教程,所以这是我的代码:

 < div id =mySidenavclass =sidenav> 
< a href =javascript:void(0)class =closebtnonclick =closeNav()>& times;< / a>
< a href =#>关于< / a>
< a href =#>服务< / a>
< a href =#>客户< / a>
< a href =#>联络人< / a>
< / div>

<! - 使用任何元素打开sidenav - >
< span onclick =openNav()>打开< / span>

JavaScript:

  / *设置侧边导航的宽度为250px,页面内容的左边距为250px * / 
函数openNav(){
document.getElementById(mySidenav)。 style.width =250px;
document.getElementById(main)。style.marginLeft =250px;


设置侧边导航的宽度为0,页面内容的左边距为0 * /
function closeNav(){
document .getElementById(mySidenav)。style.width =0;
document.getElementById(main)。style.marginLeft =0;

CSS

  / *侧面导航菜单* / 
.sidenav {

height:100%; / * 100%全高* /
宽度:0; / * 0宽度 - 用JavaScript更改* /
position:fixed; / *保持原状* /
z-index:1; / *留在最上面* /
top:0;
剩下:0;
背景颜色:#111; / *黑色* /
溢出-x:隐藏; / *禁用水平滚动* /
padding-top:60px; / *从顶部* /
转换放置60px内容:0.5s; / * 0.5秒的过渡效果在sidenav中滑动* /
}

/ *导航菜单链接* /
.sidenav a {
font-size: 20像素;
padding:5px 10px 5px 10px;
text-decoration:无!重要;
颜色:#818181;
背景:透明;
display:block;
转换:0.3s
}

/ *当您将鼠标悬停在导航链接上时,请更改其颜色* /
.sidenav a:hover,.offcanvas a:重点{
颜色:#f1f1f1;
}

/ *关闭按钮的位置和样式(右上角)* /
.sidenav .closebtn {
position:absolute;
top:0;
right:25px;
font-size:36px;
margin-left:50px;
}

.sidenav .removebtn {
color:#e9e9e9;
位置:绝对;
top:0;
left:25px;
font-size:20px;
margin-right:50px;
}

/ *样式页面内容 - 如果您想在打开侧面导航时将页面内容推送到右侧,请使用此内容* /
#main {
过渡:边缘向左.5s;
padding:20px;
}

/ *在较小的屏幕上,如果高度小于450像素,请更改sidenav的样式(减少填充和较小的字体大小)* /
@media screen和(max-height:450px){
.sidenav {padding-top:15px;}
.sidenav a {font-size:18px;}
}

我看到了包括Cookies在内的一些解决方案,但作为JS的noob,我想要一个我能理解的答案。



谢谢!

解决方案

所以如果我理解正确,当页面改变时,该栏会打开。



当页面重新加载到另一个页面时,浏览器从服务器获取新的html(即使它相同),并且洞页面重置,所以侧栏状态重置。



您可以将侧栏的状态保存在某处,以便您可以在页面再次加载时检索它。
Javascript可以访问2个存储区,Cookie和LocalStorage。



Cookie与服务器共享(浏览器将所有cookie发送到服务器请求)
,而localStorage只能由javascript访问。



服务器通常不在乎侧栏是打开还是关闭,因此正确的存储使用的是localStorage。
(w3schools中的LocalStorage) http://www.w3schools.com/html/html5_webstorage。 asp



现在你的问题,

你需要保存边栏状态,所以您在关闭或打开边栏时更新状态:

 函数openNav(){
...
//如果浏览器支持localStorage
if(typeof(Storage)!==undefined){
//将边栏的状态保存为open
localStorage .setItem(侧边栏,打开);
}
...
}

function closeNav(){
...
//如果浏览器支持localStorage
if(typeof(Storage)!==undefined){
//将边栏的状态保存为打开
localStorage.setItem(sidebar,closed) ;
}
...
}

现在我们有保存状态,我们需要在浏览器每次加载页面时检查它。
我们需要快速完成,因此我们不想等待onload事件等任何事件。
我们只需要在页面上加载侧边栏元素,而不是所有页面,所以我们可以在侧边栏元素下面输入我们的代码。

 <! - 侧边栏元素 - > 
< div id =mySidenavclass =sidenav> ...< / div>
<! - 浏览器渲染边栏后 - >
< script type =text / javascript>
//如果浏览器支持localStorage
if(typeof(Storage)!==undefined){
//如果我们需要打开bar
if( localStorage.getItem(sidebar)==opened){
//打开栏
document.getElementById(mySidenav)。style.width =250px;
document.getElementById(main)。style.marginLeft =250px;
}
}
< / script>

这有两个问题,


  1. 必须支持LocalStorage。 (Google Chrome 4.0+,Internet Explorer 8.0+,Firefox 3.5+,Safari 4.0+,Opera 11.5 +)

  2. 由于转换重播动画:。 5s; css规则。

第二个问题可以通过添加转换:.5s; 放在一个类上,并临时使用javascript删除它,直到您打开侧边栏。

 <! - 侧边栏元素 - > 
< div id =mySidenavclass =sidenav> ...< / div>
<! - 浏览器渲染边栏后 - >
< script type =text / javascript>
//如果浏览器支持localStorage
if(typeof(Storage)!==undefined){
//如果我们需要打开bar
if( localStorage.getItem(sidebar)==opened){
//从'sidebar'和'main'
...
转换时删除类//打开bar
document.getElementById(mySidenav)。style.width =250px;
document.getElementById(main)。style.marginLeft =250px;
//再次添加转换类
...
}
}
< / script>






使用Cookie



Javascript不像访问本地存储那样访问cookie。



您可以将cookie想象成一个大字符串,可以通过 document.cookie 上的变量
进行访问(所有文档cookie都在这里)

可以在控制台中看到这个变量

 > document.cookie 
a_cookie_name = cookie_value; an_other_cookie_name = and_his_value; ...

保存一个cookie,所有你需要做的是

$ p $ //按名称添加/更新一个cookie
document.cookie = name +=+ value +;

这不会清除旧的Cookie,它只会添加新的Cookie或存在它,更新它。



但是获得它们的值有点困难......你必须在变量中取出字符串,将字符串拆分为;,这样你有一个字符串数组,其中每个数组项都是一个cookie,并在数组中搜索你的cookie ......太麻烦了。



但是我们不'不得不重新发明轮子...所以我们可以使用 w3schools'code



 函数setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays * 24 * 60 * 60 * 1000));
var expires =expires =+ d.toUTCString();
document.cookie = cname +=+ cvalue +; + expires +; path = /;
}

函数getCookie(cname){
var name = cname +=;
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);

if(c.indexOf(name)== 0){
return c.substring(name.length,c.length);
}
}
return;

$ / code>

现在放弃使用localStorage,我们使用上面的函数

localStorage.getItem(sidebar)相当于 getCookie(sidebar)
$ b

localStorage.setItem(sidebar,< value>)等价物是 setCookie(sidebar,< value>,30)



(请注意,由于cookies过期,在 30 天后过期,因此要删除一个cookie,请将到期日设置为现在 -1



w3schools localStorage


im a bit of a newbie on JS stuff , mostly use bootstrap ready solutions , but now i want to implement a sidebar for my facets(filtering).

So clicking on a filter , the content is changed based on that and the page URL as well , so the sidebar closes.

What I'd like to do , is the sidebar to stay open until the user clicks the X..

I used W3School sidebar tutorial for this , so this is my code :

<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<!-- Use any element to open the sidenav -->
<span onclick="openNav()">open</span>

JavaScript:

/* Set the width of the side navigation to 250px and the left margin of the page content to 250px */
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0 */
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft = "0";
}

CSS

/* The side navigation menu */
.sidenav {

    height: 100%; /* 100% Full-height */
    width: 0; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    left: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
    padding-top: 60px; /* Place content 60px from the top */
    transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}

/* The navigation menu links */
.sidenav a {
   font-size: 20px;
   padding:5px 10px 5px 10px;
    text-decoration: none !important;    
    color: #818181;
    background: transparent;
    display: block;
    transition: 0.3s
}

/* When you mouse over the navigation links, change their color */
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

/* Position and style the close button (top right corner) */
.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

.sidenav .removebtn {
    color: #e9e9e9;
    position: absolute;
    top: 0;
    left: 25px;
    font-size: 20px;
    margin-right: 50px;
}

/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
    transition: margin-left .5s;
    padding: 20px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
    .sidenav {padding-top: 15px;}
    .sidenav a {font-size: 18px;}
}

I saw some solutions including Cookies , but being a noob in JS stuff , i'd like an answer i can understand.

Thank you!

解决方案

So if I understand correctly, you want to keep the bar open when the page change.

When the page reloads into an other one, the browser gets a new html from the server (even if it is the same), and the hole page resets, so the side bar state resets.

You can save the state of the side bar somewhere so that you can retrieve it once the page loads again. Javascript has access to 2 storages, the Cookies and the LocalStorage.

Cookies are shared with the server (the browser sends all the cookies to the server with each request) while the localStorage can be accested only by the javascript.

The server usually don't care if the sidebar is opened or closed, so the "right" storage to use is the localStorage. (LocalStorage in w3schools http://www.w3schools.com/html/html5_webstorage.asp)

To your problem now,

You need to save the sidebar state, so you update the state when you close or open the sidebar :

function openNav() {
    ...
    // If localStorage is supported by the browser
    if (typeof(Storage) !== "undefined") {
        // Save the state of the sidebar as "open"
        localStorage.setItem("sidebar", "opened");
    }
    ...
}

function closeNav() {
    ...
    // If localStorage is supported by the browser
    if (typeof(Storage) !== "undefined") {
        // Save the state of the sidebar as "open"
        localStorage.setItem("sidebar", "closed");
    }
    ...
}

Now that we have saved the state, we need to check it every time the browser loads the page. We need to do it fast, so we don't want to wait for any event like onload event. We only need the sidebar element to be loaded on the page, not all the page, so we can enter our code right under the sidebar element.

<!-- The sidebar element -->
<div id="mySidenav" class="sidenav">...</div>
<!-- Right after the browser renders the sidebar -->
<script type="text/javascript">
    // If localStorage is supported by the browser
    if (typeof(Storage) !== "undefined") {
        // If we need to open the bar
        if(localStorage.getItem("sidebar") == "opened"){
            // Open the bar
            document.getElementById("mySidenav").style.width = "250px";
            document.getElementById("main").style.marginLeft = "250px";
        }
    }
</script>

This has 2 problems,

  1. LocalStorage has to be supported. (Google Chrome 4.0+, Internet Explorer 8.0+, Firefox 3.5+, Safari 4.0+, Opera 11.5+)
  2. It replays the animation due to the transition: .5s; css rule.

The 2nd problem can be fixed by adding the transition: .5s; on a class and temporary removing it with javascript untill you open the sidebar.

<!-- The sidebar element -->
<div id="mySidenav" class="sidenav">...</div>
<!-- Right after the browser renders the sidebar -->
<script type="text/javascript">
    // If localStorage is supported by the browser
    if (typeof(Storage) !== "undefined") {
        // If we need to open the bar
        if(localStorage.getItem("sidebar") == "opened"){
            // Remove class with transition from the 'sidebar' and the 'main'
            ...
            // Open the bar
            document.getElementById("mySidenav").style.width = "250px";
            document.getElementById("main").style.marginLeft = "250px";
            // Add the transition class again
            ...
        }
    }
</script>


Using Cookies

Javascript don't access the cookies in the same way like the access to the local storage.

You can imagine cookies like a big string that can be accessed from the variable on document.cookie (all document cookies are here)

You can see this variable in the console

> document.cookie
"a_cookie_name=cookie_value; an_other_cookie_name=and_his_value; ..."

To save a cookie, all you have to do is

// Add/Update a cookie by name
document.cookie = name + "=" + value + ";"

This doesn't clear the old cookies, it only adds a new cookie or if it exist, it updates it.

But it is a little difficult to get their value... you have to get the string in a variable, split the string in "; " so that you have an array of string where each item of the array is a cookie, and search for your cookie in the array... too big trouble.

But we don't have to reinvent the wheel... so we can use w3schools' code

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Now insted of using localStorage we use the functions above

localStorage.getItem("sidebar") equivalent is getCookie("sidebar")

localStorage.setItem("sidebar","<value>") equivalent is setCookie("sidebar", "<value>", 30)

(note that because the cookies expire, we set it to expire after 30 days, so to delete a cookie, you set the expiration day to a time before now -1)

It is good to check more about cookies on w3schools and the localStorage.

这篇关于JavaScript侧边栏保持打开页面更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆