Display image on hover, centered in the background

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

I went through a number of questions regarding displaying image on hover here on Stackoverflow, but couldn't find a solution for my problem.

Right now I managed to display an image in the background of the paragraph once I hover on it. See on JSFiddle.

Ideally what would I like to do achieve: once I hover over an Example1 inside of a paragraph I would like to display Image1 in the background, not below the paragraph, but centered in the background, below all of the elements. As pictured here.

Hovering on Example2 would ideally display Image2, and Example3 would display 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'); } 

Does anyone have a solution? Many thanks.

回答1:

You can use javascript as that

    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:

you should wrap Example1 and Example2 with span tag or div and add css rules for these wraps.

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

and add 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'); } 

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



回答3:

I hope this may help you.

#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>


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!