【问题标题】:Display image on hover, centered in the background在悬停时显示图像,在背景中居中
【发布时间】:2016-05-26 22:10:55
【问题描述】:

我遇到了许多关于在 Stackoverflow 上悬停时显示图像的问题,但找不到解决我的问题的方法。

现在,当我将鼠标悬停在段落的背景上时,我设法在该段落的背景中显示了一张图片。 See on JSFiddle.

理想情况下,我想实现什么:一旦我将鼠标悬停在段落内的 Example1 上,我想在背景中显示 Image1,而不是在段落下方,而是在背景中居中,在所有元素下方。 As pictured here

将鼠标悬停在 Example2 上会显示 Image2,Example3 会显示 Image3。

HTML

<div id="imgbg">
<p>Portfolio:</p>    
<p>I worked with:<br />
Example1, Example2, Example3, Example4, Example5
</p>
</div>

CSS

#imgbg {
height: 100%;
width: 100%;
}

#imgbg:hover {
background-image: url('http://i.imgur.com/9bbjE1Mb.jpg');
}

有人有解决办法吗?非常感谢。

【问题讨论】:

    标签: html css image hover


    【解决方案1】:

    你可以像那样使用javascript

        function showBg() {
          document.body.style.backgroundImage = "url('http://i.imgur.com/9bbjE1Mb.jpg')";
        }
    
        function hideBg() {
          document.body.style.backgroundImage = null;
    
        }
    <div onmouseover="showBg()" onmouseleave="hideBg()" id="imgbg">
      <p>I worked with:
        <br />Example1, Example2, Example3, Example4, Example5
      </p>
    </div>

    【讨论】:

      【解决方案2】:

      你应该用 span 标签或 div 包裹 Example1 和 Example2 并为这些包装添加 css 规则。

      <span id="ex1">Example1</span>, <span id="ex2">Example2</span>, Example3, Example4, Example5
      

      并添加css

      #ex1, #ex2 {
         display:inline-block;
         height:50px;
      }
      
      #ex1:hover {
        background-image:url('http://i.imgur.com/9bbjE1Mb.jpg');
      }
      
      #ex2:hover {
         background-image:url('http://i.imgur.com/9bbjE1Mb.jpg');
      }
      

      https://jsfiddle.net/4tubcy8e/6/

      【讨论】:

      • 谢谢德米特里。这很好用,它解决了我问题的第一部分。如果我想在不低于 Example1、Example2 等的悬停时显示图像,解决方案是什么?但相反,以网站为中心。如图所示:i.imgur.com/QaCWBh3.jpg
      【解决方案3】:

      希望对你有帮助。

      #imgbg {
        position: relative;
        width: 100%;
        height: 265px;
      }
      
      #imgbg .Example:hover:after {
        display: block;
      }
      
      #imgbg .Example:after {
        content: '';
        display: none;
        width: 160px;
        height: 160px;
        background: url('http://i.imgur.com/9bbjE1Mb.jpg');
        background-size: contain;
        position: absolute;
        top: 50%;
        left: 0;
        margin-top: -80px;
        margin-left: 145px;
        z-index: -1;
      }
      <div id="imgbg">
        <p>Portfolio:</p>    
        <p>I worked with:<br />
         <span class="Example">Example1</span>,
         <span class="Example">Example2</span>,
         <span class="Example">Example3</span>,
         <span class="Example">Example4</span>,
         <span class="Example">Example5</span>
        </p>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-28
        • 2014-06-21
        • 2017-02-02
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        相关资源
        最近更新 更多