在 web 中如何切换一个元素的可见度?

在给定限制条件下,可通过以下纯CSS方案实现(使用复选框状态控制 + SVG遮盖交互):

<div class="container">
  <!-- 用绝对定位将交互控件隐藏到位置A和B -->
  <div style="position:absolute; left:[A的x坐标]px; top:[A的y坐标]px; z-index:2">
    <label style="display:block; width:40px; height:40px">
      <input type="checkbox" class="controller" checked style="display:none">
      <!-- 用SVG创建透明点击区域 -->
      <svg viewBox="0 0 40 40" width="40" height="40">
        <rect fill="transparent" width="100%" height="100%"/>
      </svg>
    </label>
  </div>

  <div style="position:absolute; left:[B的x坐标]px; top:[B的y坐标]px; z-index:2">
    <label style="display:block; width:40px; height:40px">
      <input type="checkbox" class="controller" style="display:none">
      <!-- 用SVG创建透明点击区域 -->
      <svg viewBox="0 0 40 40" width="40" height="40">
        <rect fill="transparent" width="100%" height="100%"/>
      </svg>
    </label>
  </div>

  <!-- 目标元素容器 -->
  <div class="target-container" style="position:relative; z-index:1">
    <div class="target-element">目标内容</div>
  </div>
  
  <!-- 利用SVG遮盖层实现视觉隐藏 -->
  <svg style="position:absolute; width:100%; height:100%; top:0; left:0; z-index:3; pointer-events:none">
    <defs>
      <mask id="hider">
        <!-- 当A被点击时显示的遮挡矩形 -->
        <rect x="0" y="0" width="100%" height="100%" fill="white" fill-opacity="0">
          <animate attributeName="fill-opacity" fill="freeze" to="1" begin="indefinite"/>
        </rect>
        <!-- 当B被点击时隐藏的遮挡矩形 -->
        <rect x="0" y="0" width="100%" height="100%" fill="white" fill-opacity="1">
          <animate attributeName="fill-opacity" fill="freeze" to="0" begin="indefinite"/>
        </rect>
      </mask>
    </defs>
    <rect x="0" y="0" width="100%" height="100%" fill="white" mask="url(#hider)"/>
  </svg>
</div>

<style>
/* 位置A的复选框被点击时:启动遮盖动画 */
.controller:nth-of-type(1):checked ~ svg mask rect:nth-of-type(1) > animate {
  begin: 0; /* 触发填充不透明变化 */
}

/* 位置B的复选框被点击时:取消遮盖 */
.controller:nth-of-type(2):checked ~ svg mask rect:nth-of-type(2) > animate {
  begin: 0; /* 触发填充透明变化 */
}
</style>

实现原理:

  1. 交互逻辑​:
    • 在位置A/B分别放置透明复选框(通过<svg>+<rect>创建40×40的点击区域)
    • 点击位置A时:触发第一个复选框的:checked状态
    • 点击位置B时:触发第二个复选框的:checked状态
  2. 视觉隐藏​:
    • 使用SVG <mask><animate>创建动态遮罩
    • 当位置A被点击时:遮罩层变为不透明(白色遮挡目标元素)
    • 当位置B被点击时:遮罩层变为透明(显示目标元素)
    • pointer-events:none确保遮罩不会拦截点击事件
  3. 状态持久化​:
    • 利用SVG动画的fill="freeze"保持最终效果
    • 依靠复选框的checked状态记忆显示/隐藏状态

注意​:需将示例中 [A的x坐标]/[A的y坐标][B的x坐标]/[B的y坐标] 替换为实际像素位置。此方案符合所有限制条件,仅使用class选择器、无脚本,通过CSS+SVG实现交互。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇