我有一系列链接来隐藏/显示六个不同的div。 我希望页面加载到隐藏所有六个div的位置。 单击六个链接之一后,相应的div 应该淡入。 单击任何其他链接时,当前应淡出,并且应显示新选择的div。
这是我放在开始正文标签内的jQuery脚本的开头:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#1").on('click', function() {
$(this).fadeOut();
$("#Graphics, #Jury, #Witness, #Mock, #Continuing").fadeOut();
$("#Strategy").fadeIn();
});
</script>
以下是链接:
<a href="#Strategy" id="1">Strategy & Theme Development</a>
<a href="#Graphics" id="2">Graphics</a>
<a href="#Jury" id="3">Jury Selection</a>
<a href="#Witness" id="4">Witness Preparation</a>
<a href="#Mock" id="5">Mock Trials & Focus Groups</a>
<a href="#Continuing" id="6">Continuing Legal Education</a>
这些是目标div:
<div id="Strategy"></div>
<div id="Graphics"></div>
<div id="Jury"></div>
<div id="Witness"></div>
<div id="Mock"></div>
<div id="Continuing"></div>
我不确定指向div 的链接是否覆盖了 jQuery 效果。
你正在寻找这样的东西:
$(document).ready(function() {
$("a").on('click', function (e) {
var currentElement = $(e.currentTarget);
var divToShow = currentElement.attr('href'); // grab the id of the div we need to show
// now find an visible divs
var visibleDiv = $('div').filter(function() { return $(this).is(':visible'); });
if (visibleDiv.length) // if there is a div already visible, fade it out then fade in the target div
{
$(visibleDiv).fadeOut(400, function() {
$(divToShow).fadeIn();
});
}
else $(divToShow).fadeIn(); // fade it in.
});
});
您已经拥有要淡化的div
的 id,通过其href
属性链接到a
标签。
我只是在控制淡入淡出divs
的 a
标签中添加一个公共类,然后在单击其中任何一个时,获取其 href
属性并在该div 中淡入淡出,同时淡出当前可见的div(如果存在)。
我还会在可淡入淡出的 div
s 中添加一个公共类,这样您就可以在不接触 DOM 的其余部分的情况下过滤它们。
JSFiddle 这里
更新:
下面是为元素提供公共类的示例:
对于a
标记,请向所有标记添加一类hideShow
:
<a href="#Strategy" id="1" class="hideShow">Strategy & Theme Development</a>
<a href="#Graphics" id="2" class="hideShow">Graphics</a>
<a href="#Jury" id="3" class="hideShow">Jury Selection</a>
etc...
对于"div"标签,请向所有标签添加一类hideable
:
<div id="Strategy" class="hideable">The strategy div</div>
<div id="Graphics" class="hideable">The Graphics div</div>
<div id="Jury" class="hideable">The Jury div</div>
etc...
然后在 jQuery 中:
$(document).ready(function() {
$(".hideShow").on('click', function (e) {
// you clicked one of the `.hideShow` a tags!
....
// now filter through all the divs with `class="hideable"` to find a visible one
var visibleDiv = $('.hideable').filter(function() { return $(this).is(':visible'); });
});
});
您应该选择元素的 ID,而不是元素的 href 值。
$("#1").on('click', function() {
$(this).fadeOut();
$("#2, #3, #4, #5, #6").fadeOut();
$("#1").fadeIn();
});
您可能想尝试单独操作它们:
$("#Graphics,#Jury,#Witness,#Mock,#Continuing").each(function(){
$(this).fadeOut();
});
您可能还想查看 .toggle()