首页 > 解决方案 > 没有 JavaScript 的图像翻转

问题描述

我正在尝试发现一种不使用 javascript 的方法,该方法允许您将鼠标悬停在较小的 div(或图像)上以更改较大 div 的背景。纯粹使用 HTML 和 CSS 是否可能?

该示例有 2 个问题: 1. 仅滚动其中一个 div 有效(因为它紧随其后) 2. 当滚动该 div 时,将鼠标移开后主 div 的背景会恢复,因此这不是永久更改

我很好奇并感谢这里的任何建议,谢谢!


更新: 我刚刚创建了这个:https ://jsfiddle.net/ehzsmusr/

背景似乎发生了变化,但是当您将鼠标悬停在其他东西上时不要停留。这可以解决吗?

#main {
  width: 300px;
  height: 200px;
  background: red;
  float: left;
}
.hover1 {
  float: left;
  background: blue;
  width: 100px;
  height: 75px;
}
.hover2 {
  float: left;
  background: green;
  width: 100px;
  height: 75px;
}
.hover1:hover + #main {
    background: #ccc
}
.hover2:hover + #main {
    background: #ccc
}
<div class='container'>
  
  <div class='hover1'></div>
  <div class='hover2'></div>
  <div id='main'></div>
</div>

标签: htmlcss

解决方案


如果您不介意按评论中提到的那样单击,这是@kabanus 提到的复选框黑客的一种实现(改用单选按钮)

body {
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  background: #eee;
}

input {
  display: none;
}

label {
  display: block;
  width: 50px;
  height: 50px;
  float: left;
  margin: 20px;
}

#redL {
  background: red;
}

#greenL {
  background: green;
}

#blueL {
  background: blue;
}

#red:checked ~ #big {
  background: red;
}

#green:checked ~ #big {
  background: green;
}

#blue:checked ~ #big {
  background: blue;
}

#big {
  width: 50vw;
  height: 50vh;
  background: #fff;
  clear: both;
  margin: auto;
}
<div id="container">
  <input type="radio" id="red" name="color" />
  <label for="red" id="redL"></label>

  <input type="radio" id="green" name="color" />
  <label for="green" id="greenL"></label>

  <input type="radio" id="blue" name="color" />
  <label for="blue" id="blueL"></label>

  <div id="big">

  </div>
</div>

另一种技巧是将设置transition-delay604800s(或更多),以便颜色改变并在该秒数(一周后)后返回。

body {
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  background: #eee;
}

#redL {
  background: red;
}

#greenL {
  background: green;
}

#blueL {
  background: blue;
}

label {
  display: block;
  width: 50px;
  height: 50px;
  float: left;
  margin: 20px;
}

#redL:hover ~ #big {
  background: red;
  transition-delay: 0s;
}

#greenL:hover ~ #big {
  background: green;
  transition-delay: 0s;
}

#blueL:hover ~ #big {
  background: blue;
  transition-delay: 0s;
}

#big {
  width: 50vw;
  height: 50vh;
  background: #fff;
  clear: both;
  margin: auto;
  transition: all .1s 604800s;
}
<div id="container">
  <label id="redL"></label>
  <label id="greenL"></label>
  <label id="blueL"></label>
  
  <div id="big">

  </div>
</div>


推荐阅读