首页 > 解决方案 > 单击按钮时更改 div 内容

问题描述

我正在尝试在我的网站上制作某种画廊。有3个按钮,下面放了一些文字和图片。当我单击按钮时,我希望内容发生变化(从按钮 #2 等内容更改)。我怎样才能做到这一点?

<ul>
  <a href="">
    <li>Btn1</li>
  </a>
  <a href="">
    <li>Btn2</li>
  </a>
  <a href="">
    <li>Btn3</li>
  </a>
</ul>

<div class="list-first"">
  <p class="list-first list-first-mobile">some text from first btn</p>
  <img src="imgs/stock1.jpeg" alt="jpg from first btn" class="list-first-img">
</div>

标签: javascripthtmlcss

解决方案


试试这个,希望对你有帮助

document.querySelectorAll('button').forEach((el, i) => {
  el.addEventListener("click", () => {
    document.querySelectorAll('p').forEach(ed => ed.style.display = "none")
    el.nextElementSibling.style.display = "block"
  })
})
<style>

.loc-caption:before {
  content: attr(title);
  display: block;
}

ul {
  text-align: center;
  padding: 0;
}

li {
  width: 25%;
  display: inline-block;
  vertical-align: top;
}

li img {
  max-width: 100%;
  height: auto;
}

 
</style>

<ul>
  <li class="loc-caption"><button>ClickME</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://chainimage.com/images/related-pictures-natural-sceneries-beautiful-wallpapers.jpg" alt="jpg from first btn " class="list-first-img "> some text from first btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME2</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRwXvWYU5tYrokWILC7lgjmCYqYGvActZnt9q8AcPs4dR7hMTBR" alt="jpg from second btn " class="list-first-img "> some text from second btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME3</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzzP-CJnW3xuNeqqMcNLzK_IFPCywsEKifAWlajEzWcdALIDLI" alt="jpg from third btn " class="list-first-img "> some text from third btn
    </p>
  </li>

</ul>


推荐阅读