猿问

刷新页面后将类保存到图标

我有这个代码:


   <div class="places-item">

      <div class="places-item-img"></div>

      <div class="places-item-header">

         <h2>Machu Picchu, Peru</h2>

         <div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>

      </div>

   </div>

   <div class="places-item">

      <div class="places-item-img"></div>

      <div class="places-item-header">

         <h2>Ciucaș Peak, Romania</h2>

         <div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>

      </div>

   </div>

.places-item {

    width: 100%;

}

.places-item-img {

    width: 100%;

    height: 350px;

  background-color: cyan;

}

.places-item-header {

    display: flex;

    justify-content: space-between;

    align-items: center;

    padding: 1em 0;

}

.places-item-header h2 {

    font-size: 24px;

    max-width: calc(100% - 38px);

}

.places-item-header-add {

    width: 28px;

    height: 28px;

    cursor: pointer;

}

.places-item-header-add svg {

    width: 100%;

    height: 100%;

}

.places-item-header-add.added svg path {

    fill: #000 !important;

}

var addBtn = document.querySelectorAll('.places-item-header-add');


for(i=0;i<addBtn.length;++i)addBtn[i].addEventListener('click',function(){

  this.classList.toggle('added');

});

当你点击该图标时,它会变成黑色。如何使刷新页面后被点击的图标(可能有多个)变成黑色?我打算在 localStorage 中执行此操作。


侃侃无极
浏览 124回答 1
1回答

慕的地6264312

针对您的元素,添加 id,以便我们可以指定哪个项目处于活动状态。例子。将 id 添加到您的项目标题中。 <div id='peru' class="places-item-header-add">当窗口加载时,检查本地存储中的值并更新项目类。var addBtn = document.querySelectorAll('.places-item-header-add');var items = JSON.parse(localStorage.getItem('selected_items')) || {};for (i = 0; i < addBtn.length; ++i) {&nbsp; if (items[addBtn[i].id]) {&nbsp; &nbsp; addBtn[i].classList.add('added');&nbsp; }&nbsp; addBtn[i].addEventListener('click', function() {&nbsp; &nbsp; this.classList.toggle('added');&nbsp; &nbsp; if (this.classList.contains('added')) {&nbsp; &nbsp; &nbsp; items[this.id] = true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; items[this.id] = false;&nbsp; &nbsp; }&nbsp; &nbsp; localStorage.setItem('selected_items', JSON.stringify(items));&nbsp; })}检查这个小提琴 https://jsfiddle.net/uwqevc65/
随时随地看视频慕课网APP

相关分类

Html5
我要回答