亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刷新頁面后將類保存到圖標

刷新頁面后將類保存到圖標

侃侃無極 2023-09-04 16:01:30
我有這個代碼:   <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 中執行此操作。
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

針對您的元素,添加 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) {

  if (items[addBtn[i].id]) {

    addBtn[i].classList.add('added');

  }

  addBtn[i].addEventListener('click', function() {

    this.classList.toggle('added');

    if (this.classList.contains('added')) {

      items[this.id] = true;

    } else {

      items[this.id] = false;

    }

    localStorage.setItem('selected_items', JSON.stringify(items));

  })

}

檢查這個小提琴 https://jsfiddle.net/uwqevc65/


查看完整回答
反對 回復 2023-09-04
  • 1 回答
  • 0 關注
  • 157 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號