好吧,我正在设计一个网站,并认为我会坚持一些jQuery,因为我真的需要这样的经验.
有问题的页面在这里:http://new.focalpix.co.uk/moreinfo.php
有问题的JS是:
$(document).ready(function(){
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideUp('slow');
var id = $(this).attr('href');
$(id).slideDown('slow');
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,但是如果您点击答案已经滑落的链接,那么它会向上滑动,然后再次向下滑动.
我不确定以最干净的方式阻止这种情况发生 - 任何想法?
您应该使用.slideToggle()效果.
$(document).ready(function() {
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideToggle('slow');
});
});
Run Code Online (Sandbox Code Playgroud)
首先,我建议您的常见问题解答的结构如下:
<div id="faq">
<div class="qa" id="faq_greenandflies">
<span class="q">What is <a href="#faq_greenandflies">green and flies</a></span>
<div class="a">
Super Pickle!
</div>
</div>
<div class="qa" id="faq_redandbadforteeth">
<span class="q">What is <a href="#faq_redandbadforteeth">Red and bad for your teeth</a></span>
<div class="a">
a Brick
</div>
</div>
<!--
More FAQ's here
-->
</div>
Run Code Online (Sandbox Code Playgroud)
然后按如下方式定义jQuery:
<script type="text/javascript">
$(function(){
// hide all answers
$('div#faq .qa .a').hide();
// bind a click event to all questions
$('div#faq .qa .q a').bind(
'click',
function(e){
// roll up all of the other answers (See Ex.1)
$(this).parents('.qa').siblings().children('.a').slideUp();
// reveal this answer (See Ex.2)
$(this).parents('.qa').children('.a').slideDown();
// return true to keep any other click events
return true;
});
// check location.hash to see if we need to expand one (direct link)
$(location.hash).find('.q a').click();
});
</script>
Run Code Online (Sandbox Code Playgroud)
说明:
(实施例1,)
(例2)
一个有效的演示是在这里.
这为你做了几件事: