【发布时间】:2022-01-11 23:05:28
【问题描述】:
在移动设备中,我正在尝试创建一个显示在图像顶部的切换开关,当点击它时,文本也会显示在图像顶部。
我基本上想重新创建The Guardian newspaper 如何处理移动设备右下角的小 (i) 图标。
在桌面上,文本默认在图像下方,并且 (i) 图标消失了。
到目前为止,我已经设法在网上其他地方找到了类似的解决方案,但它并没有像我需要的那样正常工作。
function toggleText() {
var text = document.getElementById("demo");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
#blog {
width: 100%;
}
#blog figure {
position: relative;
}
#blog figure figcaption {
display: none;
position: absolute;
bottom: 0;
left: 0;
box-sizing: border-box;
width: 100%;
color: black;
text-align: left;
background: rgba(0, 0, 0, 0.5);
}
#blog figure button {
position: absolute;
bottom: 0;
right: 0;
color: black;
border: 5px solid black;
}
<div id="blog">
<figure>
<img src="https://cdn2.hubspot.net/hubfs/4635813/marble-around-the-world.jpg" alt="A photo of a slab of marble for example">
<figcaption id="demo" style='display: none'>A photo of a slab of marble for example</figcaption>
<button type='button' onclick="toggleText()">(i)</button>
</figure>
</div>
【问题讨论】:
-
停止使用内联 JS
on*属性处理程序,就像您希望不要使用内联style属性一样(编辑:哎呀!)。 JS 和 CSS 应该只在一个地方,它们是各自的文件或标签。请改用.addEventListener()和#demo { display: none; }。 -
我知道,我也不想这样做,但如果没有那种内联显示样式:无,我必须单击/点击按钮两次才能显示标题,不理想.. .
-
你所说的不是真的。内联
display: none;等于来自 CSS 文件样式表的display: none;。想想吧。 -
如果你继续这个Fiddle 你会明白我的意思。实际上,with 内联样式属性
display:none点击按钮会显示 figcaption(应该如此)——display:none也在 CSS 中。如果我删除display:none的内联样式属性并再次运行小提琴,当我第一次单击按钮时,figcaption 不会出现,但在第二次单击时会出现。我已经重新运行小提琴几次,这就是发生的事情。我不是知识最渊博的开发人员,但据我所知,必须先初始化一些东西...... -
在这种情况下,不要检查
el.style.display === "something",而是使用developer.mozilla.org/en-US/docs/Web/API/Window/…,或者直接使用el.classList.toggle("someClassName", boolean)
标签: javascript html css