悬停效果应用于模式的悬停部分

时间:2015-09-12 11:19:18

标签: html css hover

我做了一个div并用“红盒子”模式填充它。

enter image description here

我有一个“蓝盒子”图案,我想在你将鼠标悬停在“红盒子”上时使用。

enter image description here

但是我获得了以下结果而不是上面的结果,所有“红色框”都变为“蓝框”。

enter image description here

我想将图案的悬停部分更改为“蓝框”。 我怎么能这样做?

HTML:

<div id="sample"></div>

CSS:

#sample {
  width:100vw;
  height:100vh;
  background-image:url("..\redbox.png");
}
#sample:hover {
  background-image:url("..\bluebox.png");
}
PS:以上图片仅用于说明情况,实际场景中包含较多的复杂图案。所以请考虑给出一个可以应用于任何模式的答案。

2 个答案:

答案 0 :(得分:2)

最简单的方法是制作一张桌子

&#13;
&#13;
#sample {
    width:100vw;
    height:100vh;

    ;
}
#sample table tr td{
    width:10vw;
    height:10vh;
    background-color:red;
    ;
}
#sample table tr td:hover {
    background-color:blue;
}
&#13;
<div id="sample">
    <table>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您无法仅更改背景图像的一部分,也会更改其他部分。每个元素只能定义一个background-image属性。 这就是为什么你可以使用两个div,一个在另一个之上。为此,您可以使用position属性。将其设置为relative,将top属性设置为-100vh。此值可能会根据您使用div的方式而更改。请务必进行设置,以使div重叠。

现在,您需要将光标位置放在该元素上方并获取&#34;红色框&#34;的background-position。您的用户正在将其悬停并将其应用于#sample2的{​​{1}}媒体资源,并放置&#34;蓝框&#34;在&#34;红框&#34;。

之上

HTML:

background-position

CSS:

<div id="sample1"></div>
<div id="sample2"></div>

JavaScript的:

#sample1 {
  width: 100vw;
  height: 100vh;
  background-image: url("..\redbox.png");
  background-repeat: repeat;
}
#sample2:hover {
  width: 100vw;
  height: 100vh;
  position: relative;
  top: -100vh;
  background-image: url("..\bluebox.png");
  background-repeat: no-repeat;
  background-position: -<redbox.png width>px -<redbox.png height>px;
}

请注意function hoverFunc(e) { var sideX = <redbox.png width>; var sideY = <redbox.png height>; var mouseX = e.clientX - e.target.offsetLeft; var mouseY = e.clientY - e.target.offsetTop; var posX = mouseX - (mouseX % sideX); var posY = mouseY - (mouseY % sideY); document.getElementById("sample2").backgroundPositionX = posX + "px"; document.getElementById("sample2").backgroundPositionY = posY + "px"; } function outFunc(e) { document.getElementById("sample2").style.backgroundPositionX = "-<redbox.png width>px "; document.getElementById("sample2").style.backgroundPositionY = "-<redbox.png height>px"; } document.getElementById("sample2").addEventListener("mousemove", hoverFunc, false); document.getElementById("sample2").addEventListener("mouseout", outFunc, false); 的位置,因为光标将悬停在#sample2上方。

相关问题