当鼠标在文本上时使图像出现

时间:2019-03-15 11:18:27

标签: javascript html css

我正在尝试在悬停文本时显示图像。图像不必出现在文本上,而不必出现在其他位置。

想法如下:当我将鼠标悬停在单词“ Google”上时,Google徽标必须出现在红色框中;当我将鼠标悬停在单词“ OneNote”上时,徽标OneNote必须出现在红色框中。 Step 1

我尝试遵循以下逻辑:

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>
    <body>
        <img id="img1" onmouseover="setImg()" onmouseout="unSetImg()" src="https://i1.wp.com/www.grapheine.com/wp-content/uploads/2015/09/nouveau-logo-google.gif?fit=1950%2C1200&quality=90&strip=all&ssl=1" width="300">
    </body>
    <script type="text/javascript">
        function setImg(){
            document.getElementById("img1").src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSU48ifXX9Kar3IFVrlfwx6UFLqaQno8rCebFvGtwk6yWky9_mz";
        }

        function unSetImg(){
            document.getElementById("img1").src="https://i1.wp.com/www.grapheine.com/wp-content/uploads/2015/09/nouveau-logo-google.gif?fit=1950%2C1200&quality=90&strip=all&ssl=1";
        }
    </script>
</html>

然后它起作用,但是仅当我们用另一个img代替一个img时,但是如果我改写我的代码以文本替换img google的方式,它就行不通了!

有人可以告诉我使用什么,因为我找不到与我想要的东西匹配的东西!

谢谢

卢卡斯

2 个答案:

答案 0 :(得分:0)

public class A
{
    private readonly int i;

    public A()
    {
        Action action = <.ctor>b__1_0;
        action();
    }

    [CompilerGenerated]
    private void <.ctor>b__1_0()
    {
        i = 10;
    }
}
readonly

答案 1 :(得分:0)

您可以将img src存储在要悬停的元素上的数据属性中。然后在悬停时,将img.src设置为悬停元素的data-logo

var elems = document.querySelectorAll("#thing li");
var logo = document.querySelector("#thing .logo");
elems.forEach(function(elem) {
  elem.addEventListener("mouseover", function() {
    logo.src = elem.getAttribute("data-logo");
  });
  elem.addEventListener("mouseout", function() {
    logo.src = "";
  });
});
img.logo {
  border: 2px dotted red;
  height: 50px;
  min-height: 50px;
  min-width: 50px;
}
<div id="thing">
  <img class="logo" />
  <ul>
    <li data-logo="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png">Google</li>
    <li data-logo="https://docs.microsoft.com/en-us/graph/images/onenotelogobgs.png">OneNote</li>
  </ul>
</div>