css 如何在点击锚链接时切换div的显示/隐藏

xriantvc  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(125)

我在一个页面上有一系列的div,它们的ID都是以“business”开始的。我想他们都被默认隐藏在页面加载,那么每一个都应该显示为顶部的链接点击。

按钮

<div class = "btn-wrapper">
<a href="#business-50" class="btn" target="_self">Business 50</a>
</div>
<div class = "btn-wrapper">
<a href="#business-100" class="btn" target="_self">Business 100</a>
</div>
<div class = "btn-wrapper">
<a href="#business-250" class="btn" target="_self">Business 250</a>
</div>

Divs

<div id="business-50" class="block wrapper block-11-2-three-cols-fix-tariffs-with-img"></div>
<div id="business-100" class="block wrapper block-11-2-three-cols-fix-tariffs-with-img"></div>
<div id="business-250" class="block wrapper block-11-2-three-cols-fix-tariffs-with-img"></div>

我对源代码html和css的访问权限有限,只能更改div#或运行脚本。我可以创建自定义的html块和代码我自己的按钮,但因为有一些不太精通代码的人将在未来添加/删除按钮,我很乐意在html结构中工作,因为它目前显示。
在另一个线程的建议下,我在我的覆盖文件中尝试了:

div[id^="business"] {display:none;}
div[id^="business"]:target {display:block;}

但我可能不明白选择器的用法。
我也试着修改了一些类似的东西:

$(document).ready(function(){
    $(".test").click(function(){
        $("#showme").show();
       $("#divsthatIwanttohide").hide();

    });

});
<a href="#" class="test">Say Hi</a>
<div id="showme">Howdy</div>

但我得到了一点扭转与独特的div他们正在使用。

g6ll5ycj

g6ll5ycj1#

使用jQuery为每个按钮添加单击事件侦听器

$(document).ready(function() {
  $(".btn").click(function(e) {
    e.preventDefault(); 
    var targetId = $(this).attr("href"); 
    $(targetId).show(); 
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
yftpprvb

yftpprvb2#

简单地说:

div[id^="business"]:not(:target) 
  { 
  display : none;
  }
<a href="#business-50"  class="btn" >Business 50</a>
<a href="#business-100" class="btn" >Business 100</a>
<a href="#business-250" class="btn" >Business 250</a>

<hr>

<div id="business-50"  > div business   50....</div>
<div id="business-100" > div business  100....</div>
<div id="business-250" > div business  250....</div>

在Tabs界面的情况下:

const 
  aLink   = document.querySelectorAll('a[href^="#business"]')
, divLink = document.querySelectorAll('div[id^="business"]')
  ;
aLink.forEach( (Aelm, indx) => 
  {
  let divId = Aelm.getAttribute('href').slice(1)
    ;
  Aelm.onclick =_=>
    {
    aLink.forEach( (a,i) => a.classList.toggle('select', i===indx ))
    divLink.forEach( div => div.classList.toggle('select', div.id===divId ))
    }
  })
a[href^="#business"].select   { font-weight: bold; color:red  }
div[id^="business"]:not(.select)   { display:none;  }
<a href="#business-50"  class="select" >Business 50</a>
<a href="#business-100" >Business 100</a>
<a href="#business-250" >Business 250</a>
<hr>
<div id="business-50"  class="select" > div business   50....</div>
<div id="business-100" > div business  100....</div>
<div id="business-250" > div business  250....</div>

相关问题