点击后在站点范围内更改css

时间:2017-09-24 13:21:34

标签: javascript jquery css

我尝试做的是根据所选的选项显示两个不同的菜单。 在我的代码段中,您可以看到我有option aoption b



.option-a, .option-b {
  text-transform: uppercase;
  display: inline-block;
}

.option-a:hover, .option-b:hover {
  text-decoration: underline;
}

.option-a-content {
  display: block;
}
.option-b-content {
  display: none;
}

<div class="option-a">
Option A
</div>
<div class="option-b">
Option B
</div>
<br>
<br>
<div class="option-a-content">
This is the contents of A
</div>
&#13;
&#13;
&#13;

option-a-content设为display: blockoption-b-content设为display: none;

我想点击&#39;选项B&#39;它会将option-a-content的css更改为display: none,并将其更改为display: block

编辑:为了澄清,我的问题是我可以通过点击更改css,但是当我离开页面时,它会恢复为默认值。

1 个答案:

答案 0 :(得分:0)

这是一个在localstorage中存储状态的简单示例:

$(function(){
    $(".option-toggle").on("click", function(){
        //get the href of the clicked item. This is the id of the element we wish to show
        var selectedOptionID=$(this).attr("href");
        //hide all option-content elements
        $(".option-content").attr("aria-hidden",true);
        //show the one we want
        $(selectedOptionID).attr("aria-hidden",false);
        //remember the active one in localstorage 
        localStorage.setItem("selectedOptionID", selectedOptionID);
    });

    //onload, read from local storage and trigger a click on the appropriate option:
    var selectedOptionIdFromStorage = localStorage.getItem("selectedOptionID");
    if(selectedOptionIdFromStorage){
        //trigger a click on the select-option having a href equal to selectedOptionIdFromStorage:
        $(".option-toggle[href='"+selectedOptionIdFromStorage+"']").trigger("click");
    }
});

https://jsfiddle.net/jvsnphmn/3/