【问题标题】:change div style when href link is visited访问href链接时更改div样式
【发布时间】:2015-06-06 09:12:20
【问题描述】:

我目前有一个包含此类 div 的 html 文件:

div.myClass:visited {
  background-color: red;
 }
<div class="myClass" href="link">
</div>

我在这里要做的是让 div 直接指向给定的链接,如果已经访问过该链接,则 div 背景色变为红色。该链接确实可以正常工作,但是在访问链接时更改背景颜色不起作用。有没有办法改变包含访问链接的 div 的背景颜色?谢谢!

【问题讨论】:

  • div 元素没有href 属性。如果你想链接到某个地方,为什么不直接使用a 元素呢?其他一切都没有任何意义。

标签: html css


【解决方案1】:

使用Javascript替换innerHTML

<script type = "text/javascript">
    function ReplaceContentInContainer(id, content) {
    var container = document.getElementById(id);
    container.innerHTML = content;
} </script>

<div id="example1div" style="border-style:solid;padding:10px; text-align:center;">
I will be replaced when you click.
</div>
<a href="javascript:ReplaceContentInContainer('example1div','Whew! You clicked!')">Click me to replace the content in the container.</a>

【讨论】:

    【解决方案2】:

    使用&lt;a/&gt;而不是div,并通过给它display:block;widthheight来设置div的样式

    例如:

    <a class="myClass" href="http://www.lego.com/en-us/"></a>
    

    CSS:

     .myClass {
         background-color: blue;
         width:200px;
         height:200px;
         display:block;
     }
    
    .myClass:visited {
         background-color: red;
     }
    
    .myClass:hover{
         background-color: green;
    }
    

    View on CodePin

    还请看:

    How can I detect visited and unvisited links on a page?

    Privacy and the :visited selector

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2017-04-02
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2012-08-30
      相关资源
      最近更新 更多