簡體   English   中英

如何通過單擊 div 切換 div 可見性?

[英]How to toggle div visibility by clicking a div?

我正在嘗試做一個帶有多項選擇按鈕的視覺小說小游戲,它會稍微或更多地改變故事、圖像、文本框等等……如果沒有 javascript,它就像……完全不可能。

或者可能,但它需要幾十萬頁。 誰知道。 我想避免這種情況。

所以...

有沒有辦法多次(在需要時也可以替換 100 次)可見 div 的內容 - 例如id="d01" - 包括 javascript 和 css - 用另一個類似但不可見的 div 的內容,使不可見div 可見,隱藏前一個,但點擊 div 本身?

我只能找到只能使用一次的切換和替換,然后返回到第一個內容,但我正在尋找一些不同的東西。

逐漸變化的東西,從 div 1 到 div 100 或更多。

我正在使用智能手機工作,因此編譯器或視覺小說編輯器對我來說遙不可及。 但通常網站和其他小東西,也有一些 Java,對我有用。 所以我認為這不會有什么大驚小怪的。

我知道一切都有些混亂。 對不起。

<div id="d01">

<!-- Content to show at the beginning, with everything it could come
to my mind: text, buttons, images, animations... ; -->

</div>
<div id="d02" style="display:none;">

<!-- Content to show after the first click, similar to the first, but
with light changes: other text, other characters, other images... ; -->

</div>
<div id="d03" style="display:none;">

<!-- Content to show after the second click, like as above; -->

</div>
<div id="d0#"> style="display:none;">

<!-- Content to show after the n. click... U got it at this point, i think; -->

</div>

代替在 HTML 中有很多div ,您可以只使用單個div並使用 javascript 動態替換其內容

首先,在 html 中創建一個 div 元素,並讓dialogBox作為它的 id

<div id="dialogBox">
  
</div>

在javascript中,像這樣將對話框聲明為一個數組

const dialogs = [
  {
    id: '01',
    text: "Content to show at the beginning, with everything it could come to my mind: text, buttons, images, animations... ;"
  },
  {
    id: '02',
    text: "Content to show after the second click, like as above;"
  },
  {
    id: '03',
    text: "Content to show after the n. click... U got it at this point, i think;"
  }
];

在那里放什么取決於你,但在這種情況下,我只放了textid id目前並不是必需的,但我們可以使用它進行查詢,因為將來會有數百個。

現在,找到我們的div元素並將其存儲到一個變量中

const dialogBox = document.getElementById('dialogBox');

最后,我們現在可以更新/替換我們的div內容。 在這個例子中,我們將在每次鼠標點擊時更新內容

let index = 0;
dialogBox.innerHTML = dialogs[index].text

window.addEventListener('click', () => {
  index = (index < dialogs.length - 1) ? ++index : index;
  dialogBox.innerHTML = dialogs[index].text
});

在上面的示例中,我們將其內容的div innerHTML 設置為當前對話框文本。 然后,每次單擊鼠標時將index值增加 1,然后再次更新 innerHTML。

我們完成了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM