【问题标题】:Change div background and characteristics on link click using pseudo classes使用伪类更改链接单击时的 div 背景和特征
【发布时间】:2022-01-24 05:35:08
【问题描述】:

大家好。我有一个关于单击链接时更改 div 元素的问题。

我所拥有的是 2 个名为 LINK 1 和 LINK 2 的链接,它们以水平顺序排列在代码的头部。然后左边有2个div,垂直排列,分别命名为DIV 1和DIV 2。它的作用是让特定的div在点击对应的链接时改变其背景颜色(LINK 1到DIV 1,反之亦然) .但是我遇到了无法更改 div 的问题。有没有办法纠正它?谢谢。

代码如下:

<!DOCTYPE html>
<head>
      <style>
                ul {list-style-type: none; margin: 0; padding: 0; background-color: rgb(42,157,143);overflow: hidden;}
                li{float: left;} 
                li a:link{display: block; color: black; padding: 10px; text-decoration: none;}
                li a:visited{color: orange;}
                li a:hover {background-color: rgb(38,70,83); color: blue;}
                li a.active {background-color: rgb(138,177,125); color: red;}
                
                div.top:hover {center-align:0; margin:20px; width: 40%; border: solid; padding:0;}
                div.top: active {center-align:0; margin:20px; width: 40%; border: solid; padding:0; background-color: green;}
                #link1:active div.top {display: block;}
                div.bottom:hover {center-align:0; margin:20px; width: 40%; border: solid; padding:0;}
                div.bottom: active {center-align:0; margin:20px; width: 40%; padding:0; background-color: blue; border: 10px dotted green;}
                #link2:active div.bottom {display: block;}
                
      </style>
</head>
      <body>
            <nav>
                 <ul>
                     <li><a href="#link1" target="_blank">LINK 1</a></li>
                     <li><a href="#link2" target="_blank">LINK 2</a></li>
                  </ul>
             </nav>
             <div class="top"; style="center-align:0; margin:20px; width: 40%; border: solid; padding:0;">
             <h1 style="text-align:center;"> DIV 1 <h1>
             </div>
             <div class="bottom"; style="center-align:0; margin:20px; width: 40%; border: solid; padding:0;">
             <h1 style="text-align:center;"> DIV 2<p>
             </div>
             
       </body>
</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    点击链接 - 链接 1 和链接 2。这是你想要达到的目标吗?

    alpha = (a) => {
      if(a === 'div1'){
      document.getElementById(a).style.background = "yellow";
      }
      else {
      document.getElementById(a).style.background = "green";
      }
    }
       div {height:100px; width:100px; border: 2px solid black;}
    <nav>
      <ul>
        <li><a onclick="alpha('div1')" >LINK 1</a></li>
        <li><a onclick="alpha('div2')" >LINK 2</a></li>
      </ul>
    </nav>
    
    <div id="div1"></div>
    
    <div id="div2"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-20
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2012-06-09
      • 2015-11-06
      相关资源
      最近更新 更多