首页 > 解决方案 > 具有动态内容的可转换 div

问题描述

正如标题所示,我正在尝试使用动态内容编写可转换的 div。基本上我希望 div 的文本在鼠标悬停时改变。下面是我的代码,我从没想过 ul 在鼠标悬停之前会在 div 中显示项目符号。

编辑 澄清我希望 div 有一个默认文本,即“word”,然后在悬停时它变为“Word to your mom”,然后当鼠标离开元素时,它会变回“Word”。

<!DOCTYPE html>
<html lang="en">
<style>
    .wrap{
        margin: 30px auto;
        max-width: 1000px;
        width: 90vw;
        display: flex;
        flex-flow: row wrap;
        justify-content: center;
        font-family: sans-serif;
    }

    .blue{
        background-color: rgba(56, 207, 248, 0.5);
    }

    .scale{
        transform: scale(1, 1);
        transition: transform 0.5s ease;
    }

    .box{
        width: calc(20%);
        margin: 20px 20px;
        background: #ddd;
        cursor: pointer;
        color: #FFF;
        text-align: center;
        line-height: 130px;
    }

    .box:hover .scale{
        transform: scale(1.5, 1.5);
    }

</style>

<head>
    <title></title>
<meta charset="utf-8">
</head>

<body>

    <div class="wrap">
        <div class="box">
            <div class="blue scale">
                <ul id="content">
                    <li onmouseout="Default('word')"></li>
                    <li onmouseover="hover('Word to your mother')"></li>
                </ul>

            </div>
        </div> 
    </div>
</body>

<script>
        function hover(description) {
            console.log(description);
            document.getElementById('content').innerHTML = description;
        }

        function Default(description){
            console.log(description);
            document.getElementById('content').innerHTML = description;
        }

</script>
</html>

以下是我在尝试解决此问题时访问的资源。

https://www.sitepoint.com/community/t/text-change-on-div-hover/216212/2

https://codepen.io/vailjoy/pen/ZLLLYd

根据鼠标悬停在不同的 div 上更改 div 内容

谢谢您的帮助。

标签: javascripthtmlcsstransformdynamic-content

解决方案


您当然可以在没有任何 JavaScript 的情况下完成此操作。如前所述,一种选择是使用 CSS 伪选择器和内容属性。

但是,这种方法使用了一些技巧,如果您的文档包含您想要的内容会更好。

.wrap {
  margin: 30px auto;
  max-width: 1000px;
  width: 90vw;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  font-family: sans-serif;
}

.blue {
  background-color: rgba(56, 207, 248, 0.5);
}

.scale {
  transform: scale(1, 1);
  transition: transform 0.5s ease;
}

.box {
  width: calc(20%);
  margin: 20px 20px;
  background: #ddd;
  cursor: pointer;
  color: #FFF;
  text-align: center;
  line-height: 130px;
}

.box:hover .scale {
  transform: scale(1.5, 1.5);
}

.scale span {
  display: none;
}

.box:hover .scale span {
  display: inline;
}

https://codepen.io/eheisler/pen/bmMwre


推荐阅读