我有一些 div,每个 div 都有不同的背景颜色。基于每个 anchor ,我单击一些 div 被隐藏并显示一个。我的问题是,当我用 id=next
单击 anchor 时显示下一个 div,我无法更改背景颜色,我创建了一个函数,但它不起作用,有人可以帮我解决这个问题吗?
我的 jsfiddle:DEMO
我的 HTML 代码:
<body>
<div class="info-right-div" id="right-info1" style="display: block;">
<p> div-1- <br/> Content of div 1: color is YELLOW </p>
</div>
<div class="info-right-div" id="right-info2" style="display: none;">
<p> div-2- <br/> Content of div 2 : color is RED </p>
</div>
<div class="info-right-div" id="right-info3" style="display: none;">
<p> div-3- <br/> Content of div 3: color i GRAY </p>
</div>
<br /><br /> <br />
<a id="info1" href="#"> show div 1</a>
<a id="info2" href="#"> show div 2</a>
<a id="info3" href="#"> show div 3</a>
<a id="next" href="#"> next div</a>
<br /><br /> <br />
</body>
我的 jQuery 代码:
$(document).ready(function() {
jQuery("a").click(function() {
var id = jQuery(this).attr("id");
switch (true) {
case (id == 'info1') :
$(".info-right-div").hide();
$('#right-info1').show();
$("body").css('background-color', '#FFFF00');
break;
case (id == 'info2'):
$(".info-right-div").hide();
$('#right-info2').show();
$("body").css('background-color', '#FF0000');
break;
case (id == 'info3'):
$(".info-right-div").hide();
$('#right-info3').show();
$("body").css('background-color', '#00FF00');
break;
case(id == 'next'):
var div1vis = $(".info-right-div").filter(':visible');
var id = jQuery(this).attr("id");
if (div1vis.next().length > 0) {
div1vis.next().show().prev().hide();
var nextid = div1vis.prev().attr("id");
changebackground(nextid);
}
break;
};
});
});
function changebackground(divid) {
if (divid == 'right-info1') { $("body").css('background-color', '#FFFF00'); }
if (divid == 'right-info1') { $("body").css('background-color', '#FF0000'); }
if (divid == 'right-info1') { $("body").css('background-color', '#00FF00'); }
}
当我点击 ID 为 next
的 anchor 时与 var nextid = div1vis.prev().attr("id");
我试图获取显示的 div 的 ID。
最佳答案
看看这个。这是不同的方法,但它做同样的事情 https://jsfiddle.net/8k3kp6uu/1/
HTML
<div class="background-divs green active"></div>
<div class="background-divs blue"></div>
<div class="background-divs yellow"></div>
<ul class="links">
<li><a class="link" data-background="green" href="">GREEN</a></li>
<li><a class="link" data-background="blue" href="">BLUE</a></li>
<li><a class="link" data-background="yellow" href="">YELLOW</a></li>
<li><a class="next" href="link" href="">NEXT</a></li>
</ul>
JS
$('.link').click(function(e) {
e.preventDefault();
var color = $(this).attr('data-background');
$('.background-divs').removeClass('active');
$('.background-divs.'+color).addClass('active');
});
$('.next').click(function(e) {
e.preventDefault();
var next = $('.background-divs.active');
var first = $('.background-divs').first();
var last = next.last();
next.removeClass('active').next().addClass("active");
if(next.is(last)) {
next.removeClass('active');
first.addClass('active');
}
});
关于javascript - 在下一个 div 单击中更改 div 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058546/