有没有办法简化 Javascript 的多重 if?
我有这段代码可以在滚动到其他 div 时显示三个不同的 div,但我是 javascript 的新手,我尝试先声明所有变量,但我不确定如何编写 if 部分
$(document).ready(function () {
var topOfOthDiv1 = $("#cuidamos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv1) { //scrolled past the other div?
$("#cuidado").fadeIn(); //reached the desired point -- show div
} else {
$('#cuidado').fadeOut();
}
});
});
$(document).ready(function () {
var topOfOthDiv2 = $("#productos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv2) { //scrolled past the other div?
$("#sabor").fadeIn(); //reached the desired point -- show div
} else {
$('#sabor').fadeOut();
}
});
});
$(document).ready(function () {
var topOfOthDiv3 = $("#encuentranos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv3) { //scrolled past the other div?
$("#locat").fadeIn(); //reached the desired point -- show div
} else {
$('#locat').fadeOut();
}
});
});
最佳答案
摆脱那些冗余的 .ready()
和 .scroll()
处理程序,并将所有内容放在一个。
然后将每个要淡入淡出的元素的ID做一个映射到原来的.offset().top
位置。
然后在.scroll()
handler中,迭代map,使用每个的ID和top值与当前scrollTop()
位置进行比较来决定是否应该褪色。
if
语句本身也可以通过使用方括号和条件运算符 选择要动态调用的方法的名称来消除。
$(function () {
var tops = {
cuidaado: $("#cuidamos").offset().top - 490,
sabor: $("#productos").offset().top - 490,
locat: $("#encuentranos").offset().top - 490
};
$(window).scroll(function () {
var top = $(window).scrollTop();
$.each(tops, function(id, this_top) {
$("#" + id)[top > this_top ? "fadeIn" : "fadeOut"]();
});
});
});
关于javascript - 如何简化 Javascript Multiples if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394851/