好的,怎么样 - 首先让我们对您的 html 进行一些更改。
让我们不要使用 id,而是进入按类名引用的心态。因此,对于每个内容 div,我添加了一个 news-content 类
...
<div class="news-content" id="myContent">
...
<div class="news-content" id="myContent2">
...
<div class="news-content" id="myContent3">
...
接下来让我们从超链接的 href 属性中删除点击处理程序(我们稍后将使用 jQuery 添加一个处理程序)
<a class="toggle" href="#">
删除了所有的 CSS 并确保新闻内容默认隐藏
.news-content {
display: none;
}
jQuery
有了这些更改,让我们为超链接编写一个单击处理程序,以便它执行切换。注意:我使用 slideUp 和 slideDown 而不是 toggle。
Click here for the fiddle
$(document).ready(function () {
$('a.toggle').click(function () {
// select out the elements for the clicked item
var $this = $(this),
$root = $this.closest('.news-text'),
$content = $root.find('.news-content'),
$toggleImage = $this.find('img');
// collapse all items except the clicked one
$('.news-text').each(function () {
var $itemRoot = $(this);
if ($itemRoot == $root) return; // ignore the current
var $itemContent = $itemRoot.find('.news-content');
if ($itemContent.is(':hidden')) return; // ignore hidden items
// collapse and set img
$itemContent.slideUp();
$itemRoot.find('.toggle > img').attr('src', 'http://www.70hundert.de/images/toggle-open.jpg');
});
// for the current clicked item either show or hide
if ($content.is(':visible')) {
$content.slideUp();
$toggleImage.attr('src', 'http://www.70hundert.de/images/toggle-open.jpg');
} else {
$content.slideDown();
$toggleImage.attr('src', 'http://www.70hundert.de/images/toggle-close.jpg');
}
// stop postback
return false;
});
});
更新 - 新版本的 JQuery 处理程序
Click here for the fiddle
$('a.toggle').click(function () {
var openImgUrl = 'http://www.70hundert.de/images/toggle-open.jpg',
closeImgUrl = 'http://www.70hundert.de/images/toggle-close.jpg';
var $newsItem = $(this).closest('.news-text'),
$newsContent = $newsItem.find('.news-content'),
isContentVisible = ($newsContent.is(':visible'));
// slide up all shown news-items - but its expected that only one is visible at a time
$('.news-text').find('.news-content').slideUp(function () {
// on animation callback change the img
$('.news-text').find('.toggle > img').attr('src', openImgUrl);
});
if (!isContentVisible) { // if the new-item was hidden when clicked, then show it!
$newsContent.slideDown(function () {
// on animation callback change the img
$newsItem.find('.toggle > img').attr('src', closeImgUrl);
});
}
return false; // stop postback
});