我目前正在我的网站上工作,并没有太多问题学习/搞清楚HTML和CSS。虽然我的FAQ页面使用jQuery有问题。我想把我的问题的风格从开放到封闭。虽然无论我在哪里尝试并放置切换它只会在点击时改变样式。
这是我的代码:
<script type="text/javascript">
$(document).ready(function () {
$('dd').hide()
$('dt').click(function () {
var par = $(this).next();
$('dd').each(function () {
if ($(this) !== par) {
$(this).hide(1000);
}
});
if (par.is(':visible')) {
par.hide(1000);
} else {
par.show(1000);
$(this).toggleClass('open');
}
});
});
</script>
这是CSS(因为我通过帖子/其他网站学习,所以可能有点多余):
dl.faq dt {
color: #268bd2;
font-weight: bold;
cursor: pointer;
margin: 0 0 10px 0;
padding: 0 0 10px 20px;
background: url(images/faqarrow.png) 0 0 no-repeat;
line-height: 16px;
border-bottom: 1px solid rgb(225, 225, 225);
}
dl.faq dd{
margin: 0 0 10px 0;
padding: 0 0 10px 20px;
background-color:#ededed;
}
dl.faq dt:hover {
color: #2aa198;
background-position: 0 -32px;
background: url(images/faqarrow.png) 0 0 no-repeat;
}
dl.faq dt.close{
color: #268bd2;
background-position: 0 -32px;
background: url(images/faqarrow.png) 0 0 no-repeat;
}
dl.faq dt.open{
color: #2aa198;
background-position: 0 -32px;
background: url(images/faqarrowdown.png) 0 0 no-repeat;
}
dl.faq dt.open:hover {
background-position: 0 -96px;
background: url(images/faqarrowdown.png) 0 0 no-repeat;
}
目前.open样式有效,但当点击另一个问题时它不会回到关闭的样式。我很想知道这个!
答案 0 :(得分:1)
根据您所需的操作,我们有几种方法可以执行此任务。在我的例子中,我将简单地使用将打开和关闭的<div>
。这两个都将依赖于您已经关闭所有元素,通过类名或默认样式。
第一种方法,如果开启和关闭不依赖于其他元素,您只需切换开放类。
$('div').click(function(){
$(this).toggleClass('open');
};
第二种方法,如果打开项目应该关闭其他方法。
$('div').click(function(){
$('div').removeClass('open');
$(this).addClass('open');
};
这两种方法都会处理您的问题,并且比您当前实施的方法更容易维护。
答案 1 :(得分:0)
[...]
if (par.is(':visible')) {
par.hide(1000);
$(this).toggleClass('close');
} else {
par.show(1000);
$(this).toggleClass('open');
}
[...]