gpt4 book ai didi

JQuery简单选项卡程序不显示嵌套的Div标签

转载 作者:行者123 更新时间:2023-12-01 07:01:09 25 4
gpt4 key购买 nike

此代码可以很好地显示主 div 标签元素,但忽略或无法识别子 div 标签中的 CSS 和 HTML。

我可以使用此代码打开多个 div,但不能打开嵌套在第一级 div 内的 div。 6 小时后,我希望得到外界的帮助。

这是代码:

<html>
<head>
<style type="text/css">
#tabs {
margin:20 px 0;
}

#tabs ul {
float: center;
background: #003333;
height:25px;
width: 500px;
padding-top: 4px;
}

#tabs ul li {
float: left;
margin-left: 2em;
}

#tabs ul li a {
text-decoration:none;
color:#FFFFFF;
font-weight:bold;
}

#tabs ul li.active {
background-color:#669999;
}

#tabs div {
position:absolute;
width:500px;
height:500px;
padding:20px;
margin-top:2px;
}

#tab1 {
background-color:green;
}

#tab2 {
background-color:red;
}

#blueBox {
float:left;
width:100px;
height:100px;
background-color:yellow;
margin-left:5px;
margin-top:150px;
}
</style>

<script src="js/jquery-1.4.2.js" type="text/javascript" /></script>
<script type="text/javascript">
$(document).ready(function() {
$('#tabs div').hide();
$('#tabs div:first').fadeIn('slow');
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function() {
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var selectedTab=$(this).attr('href');
$('#tabs div').fadeOut('slow');
$(selectedTab).fadeIn('slow');
return false;
});
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li><a href='#Tab1'>Tab 1</a></li>
<li><a href="#Tab2">Tab 2</a></li>
</ul>
<div id="Tab1">
<p>Contents in Tab1 </p>
</div>

<!--this next part is the part I can't get to work. The div blueBox inside the div Tab2-->

<div id="Tab2">
<p>Contents in Tab2</p>
<div id="blueBox">
<p>Hello</p>
</div>
</div>
</div>

</body>
</html>

我相信这与没有低于父级别来获取嵌套div有关,但尽管通宵达旦,但仍无法通过谷歌搜索解决方案。这是一段很棒的小代码,但如果我无法让嵌套的 div 标签正常工作,那么它就不实用。

提前致谢。

最佳答案

您只想隐藏和显示#tabs 的直接子级。 Tab1Tab2 内的其他 div 应保持原样。要实现此目的,请使用 the direct child selector ( > )

为了让事情正常工作,请将使用 #tabs div 的行更改为 #tabs > div 2 行:

    $('#tabs > div').hide();                         // <== direct child selector
$('#tabs > div').fadeOut('slow'); // <== direct child selector

但还有一些其他改进。

  1. $('#tabs ul li').removeClass('active'); 更改为 $('#tabs ul li.active').removeClass(' active');,因为使用 active 类而不是所有 li 简单地选择感兴趣的元素会更有效。

  2. fadeOut的回调中包含fadeIn,这将使事情看起来更平滑一些,因为它确保fadeIn code> 仅在 fadeOut 结束后开始。事实上,加上 .delay() 后,整个事情看起来好多了。

.

$(function() {                                   // <== shorter form of doc ready
$('#tabs > div').hide();
$('#tabs div:first').fadeIn('slow');
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function(){
$('#tabs ul li.active').removeClass('active'); // <== Only what you need
$(this).parent().addClass('active');
var selectedTab=$(this).attr('href');
$('#tabs > div').fadeOut('slow', function() { // <== Use a callback
$(selectedTab).delay(500).fadeIn('slow'); // <== add a delay
});
return false;
});
});

<强> jsFiddle example

关于JQuery简单选项卡程序不显示嵌套的Div标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847152/

25 4 0