【问题标题】:How to replace content of a div with content from pseudo class on hover如何在悬停时用伪类的内容替换 div 的内容
【发布时间】:2017-06-06 01:00:08
【问题描述】:

 body{
        font-size: 24px;
        display: flex;
        justify-content: center;
        margin: 75px 0;
    }
    
    .button{
        
        padding: 1px 3px 2px;
        font-weight: bold;
        color: #ffffff;
        text-transform: uppercase;
        white-space: nowrap;
        background-color: #bfbfbf;
        border-radius: 3px;
        text-decoration: none;
        max-height: 24px;
        
        }
    
    .button:hover{
       display:"none";
      
        }
    
    .button:hover:after{
        content: 'my second box';
        cursor: crosshair;
        background-color: #46a546;
		
        }
<body>
    
     <div class="button">my first box</div>

    
</body>

这里有一些jsfiddle 来修补。我觉得我已经尝试了每一种组合来完成这项工作!关于我需要对此代码进行哪些更改以阻止原始框移动到一边的任何想法?

【问题讨论】:

  • 你为什么不试试display:none; 而不是display:"none"
  • 删除引号是一个好的开始,但我也发现:hover:after 的工作方式存在问题,不确定它是否应该以这种方式使用。
  • 去掉引号,悬停时你会开始看到闪烁。请参阅此答案stackoverflow.com/questions/5844622/… 了解原因。

标签: html css


【解决方案1】:

如果目标是在悬停时将.button 中的内容替换为:after 伪类的内容,那么您将需要引入另一个元素。当你隐藏一个元素时,它的伪元素也将被隐藏。您可以通过在要隐藏的内容周围嵌套span 来做到这一点,然后隐藏跨度,然后在悬停时用父元素的伪元素中的内容“替换”跨度的内容 - 就像这样。 (ps - 您需要删除 display: "none"; 中的引号 - 应该改为 display: none;

body {
  font-size: 24px;
  display: flex;
  justify-content: center;
  margin: 75px 0;
}

.button span {
  padding: 1px 3px 2px;
  font-weight: bold;
  color: #ffffff;
  text-transform: uppercase;
  white-space: nowrap;
  background-color: #bfbfbf;
  border-radius: 3px;
  text-decoration: none;
  max-height: 24px;
  display: block;
}

.button:hover span {
  display: none;
}

.button:hover:after {
  content: 'my second box';
  cursor: crosshair;
  background-color: #46a546;
}
&lt;div class="button"&gt;&lt;span&gt;my first box&lt;/span&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2014-06-17
    相关资源
    最近更新 更多