我正在使用jquery切换来隐藏一些内容,如果用户希望查看,则可以“展开”这些内容。这是它的一个jsFiddle:
http://jsfiddle.net/yjs2P/
使用此代码:
$.noConflict();
function toggleDiv(divId) {
jQuery("#"+divId).toggle($);
}
如您所见,第一个元素已经用“关闭”图像(红色)打开,其他两个元素已用“打开”图像(橙色)“关闭”。
现在,我想要实现的是,如果用户单击其中一张图像,则所有切换元素都将关闭,而与点击相关的元素将被打开。元素打开时,图像应更改为其他状态,因此,如果元素关闭(橙色),则图像也应更改为打开(红色),反之亦然。
谁能为我提供有关此问题的任何提示?
提前加油!
最佳答案
好的,如何处理-首先让您对html进行一些更改。
让我们不要使用id,而要进入按类名进行引用的思想。因此,对于每个内容div,我添加了一个新闻内容类
...
<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而不是切换。
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
});