我是JS的新手,所以请耐心等待。
我正在尝试创建一个基本的内容切换,但是我很难让我的代码只显示一次切换。
我使用的代码是:
<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
<div class ="toggle" id="box1">
box one content
</div>
<div class ="toggle" id="box2">
box two content
</div>
$("a").click(function(){
var myelement = $(this).attr("href")
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide();
});
答案 0 :(得分:0)
它一次只显示一个项目。点击它们,您将看到:
$("a").click(function(){
var myelement = $(this).attr("href")
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide();
});
&#13;
<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
<div class ="toggle" id="box1">
box one content
</div>
<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
&#13;
JSFiddle:https://jsfiddle.net/xd146x1s/2/
如果您想在开始时隐藏元素,请使用$(".toggle").hide();
,例如:
$(".toggle").hide();
$("a").click(function(){
var myelement = $(this).attr("href")
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide();
});
&#13;
<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
<div class ="toggle" id="box1">
box one content
</div>
<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
&#13;
JSFiddle:https://jsfiddle.net/xd146x1s/3/
答案 1 :(得分:0)
为了一次显示一个切换,你需要比slideToggle提供更多的控制,因为你正在处理两个相反的情况,你想要显示的元素的slideDown,以及其余部分的滑动。
//By default they all will be hidden
$('.toggle').hide();
$("a").on('click', function(){
//fetch the element wrapped with jQuery
var $myelement = $($(this).attr("href"));
//Hide all elements but the selected one
//and shows it at the same time, since jQuery
//returns the object right back to allow chaining
$('.toggle').not($myelement.slideDown('slow')).slideUp("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
<div class ="toggle" id="box1">
box one content
</div>
<div class ="toggle" id="box2">
box two content
</div>