为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过单击 div 来切换 div 可见性?

如何通过单击 div 来切换 div 可见性?

跃然一笑 2023-03-03 10:46:25
我正在尝试做一个带有多个选择按钮的视觉小说小游戏,它会略微或更多地改变故事、图像、文本框等……如果没有 javascript,这就像……完全不可能。或者可能,但它需要数十万页。谁知道。我想避免这种情况。所以...有没有办法用另一个类似但不可见的 div 的内容多次(需要时也是 100 次)替换可见 div 的内容 -id="d01"例如 - 包括 javascript 和 css - 使不可见的 div 可见,隐藏以前,但点击 div 本身?我只能找到只能使用一次的切换和替换,然后返回到第一个内容,但我正在寻找有点不同的东西。逐渐变化的东西,从 div 1 到 div 100 或更多。我在智能手机上工作,所以编译器或视觉小说编辑器对我来说是遥不可及的。但通常网站和其他小东西,也有一点 java,对我有用。所以我认为这不会大惊小怪。我知道一切都有些混乱。对不起。<div id="d01"><!-- Content to show at the beginning, with everything it could cometo my mind: text, buttons, images, animations... ; --></div><div id="d02" style="display:none;"><!-- Content to show after the first click, similar to the first, butwith 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>
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

div而不是在 HTML 中有很多,你可以只使用一个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;"

  }

];

放什么取决于你,但在这种情况下,我只是放text和id。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。


查看完整回答
反对 回复 2023-03-03
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号