You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在xaringan幻灯片中实现鼠标悬停显示图片的问题求助

在Xaringan幻灯片中实现鼠标悬停显示图片的修复方案

我在普通HTML网页中测试了一套鼠标悬停显示图片的代码,能正常生效,但放到R的Xaringan幻灯片里就没用了。相关代码如下:

原CSS代码

.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

body:not(.mobile) .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;

/* Change width and height to scale images */
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
}  

原HTML代码

<div class = "hover-title">
      Default Setting
      </div> 
      <div class = "hover-image">
        <img src="https://images.unsplash.com/photo-1486312338219-ce68d2c6f44d?w=752&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" alt="">
</div>

问题原因

Xaringan基于remark.js构建,幻灯片的结构和默认样式会干扰原有CSS规则,核心问题包括:

  • 原CSS使用的body:not(.mobile)选择器不匹配Xaringan的幻灯片容器结构,幻灯片内容实际嵌套在.remark-slide-content中
  • .hover-image的z-index: -1层级过低,会被幻灯片内容容器覆盖
  • 兄弟选择器+需要确保两个元素处于同一张幻灯片的上下文内

修复后的代码

修改后的CSS

.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

/* 适配Xaringan的幻灯片容器,确保选择器匹配 */
.remark-slide-content .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* 提高层级确保显示在幻灯片上方 */
    z-index: 9999;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
    /* 可选:添加背景和阴影提升显示效果 */
    background: #fff;
    padding: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

保留原HTML结构(需确保在同一张幻灯片内)

<div class="hover-title">Default Setting</div> 
<div class="hover-image">
  <img src="https://images.unsplash.com/photo-1486312338219-ce68d2c6f44d?w=752&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" alt="">
</div>

使用说明

  1. 将修改后的CSS添加到Xaringan幻灯片的样式文件中,或直接在幻灯片开头用<style>标签嵌入
  2. 确保.hover-title和.hover-image元素位于同一张幻灯片内,兄弟选择器才能正常触发
  3. 若需在多张幻灯片使用,重复上述HTML结构即可,每个幻灯片的悬停元素相互独立

内容的提问来源于stack exchange,提问作者pinawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:20:43