【问题标题】:How to change the displayed image using HTML without JS?如何在没有 JS 的情况下使用 HTML 更改显示的图像?
【发布时间】:2022-11-17 18:57:43
【问题描述】:

我写了以下代码:

<div class="slider-button-next slider-btn"> &lt; </div>
<img src="images/pic02.jpg" alt="" data-position="center center" />
<div class="slider-button-prev slider-btn"> &gt; </div>

我希望用户单击左/右按钮以在图像之间切换。目前我只有一张图片pic02.jpg。如何在没有 JS 的情况下更改显示的图像? (例如,按右键变为pic03.jpg,按左键变为pic01.jpg等)。我打算使用托管服务来托管我的静态网站,据我所知,我不能使用 JS。

【问题讨论】:

  • 如果你用 JS 做这个不算是动态的,你可以继续使用 JS
  • 如果你可以加载 HTML,你总是可以使用 JS。作为客户端
  • @owenized 不,您不能依赖 JS 始终可用:每个网络浏览器都允许用户禁用 JS(甚至是 iOS 上的 Safari)。许多以隐私为中心的浏览器(例如 Tor)默认禁用 JS。像 Lynx 这样的文本模式浏览器根本不支持 JS,许多网络爬虫也只支持 HTML。
  • 任何原因?没有js,就不可能改变src属性。编辑:因为你提到了所有这些浏览器,所以担心的是 OP 认为静态托管不能加载 JS。
  • 我认为静态托管 = 没有 JS。是不是真的?

标签: javascript html css


【解决方案1】:

如果您对放置元素的位置很小心,可以这样做:

#mycheckbox~.images img:first-child {
  display: none;
}

#mycheckbox:checked+.images img:last-child {
  display: none;
}

#mycheckbox:checked+.images img:first-child {
  display: unset;
}
<input id='mycheckbox' type='checkbox'> Click me
<div class='images'>
  <img src='https://picsum.photos/id/237/200/300'>
  <img src='https://picsum.photos/id/433/200/300'>
</div>

:has() 伪类即将到来(它还没有在 Firefox 中 - 检查 caniuse.com 但它即将到来)这给了你很多灵活性:

.images img:first-child {
  display: none;
}

body:has(#mycheckbox:checked) .images img:last-child {
  display: none;
}

body:has(#mycheckbox:checked) .images img:first-child {
  display: unset;
}
<input id='mycheckbox' type='checkbox'> Click me
<p> Lots of content here</p>
<div class='images'>
  <img src='https://picsum.photos/id/237/200/300'>
  <img src='https://picsum.photos/id/433/200/300'>
</div>

您必须查看您的滑块元素以查看它是如何在 DOM 中呈现的,以查看它是否是基础复选框或其他输入并相应地更改规则。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2016-06-09
    • 2021-09-20
    相关资源
    最近更新 更多