如何通过使用jQuery的函数执行此特定任务?

时间:2014-01-12 09:30:37

标签: javascript jquery

我正在研究这个垂直滚动图库。 现在我无法解决这个问题,但我需要让这些代码更简洁。 我写的代码是重复的。 这是代码

var target1 = $("#myImg1").offset().top;
var target2 = $("#myImg2").offset().top;

if ($(window).scrollTop() >= target1 - 150 
 && $(window).scrollTop() <= target1 + 150) {
    showBgOnTop('#firstImage','#secondImage');  
}
if ($(window).scrollTop() >= target2 - 150 
 && $(window).scrollTop() <= target2 + 150) {
    showBgOnTop('#secondImage','#firstImage');
}

我可以在这里使用某种功能来缩短代码。 就像阵列一样 请告诉我这里我做错了什么。 感谢。

3 个答案:

答案 0 :(得分:1)

说明

看起来你有一个jQuery对象作为你的目标链接到两个图像,你想要有多个这样的实例,比如说至少2个。

所以我的解决方案是拥有一个具有这种格式的对象数组

var array = [
    {target: ['image1', 'image2']}
]

target是目标元素id,值是关联图像的ID数组。

现在,用户所要做的就是继续以上面显示的格式向阵列添加新对象。

解决方案

// Put the target object id as keys and the array of the linked/associated elements as values
var arrs = [
        {'#myImg1': ['#firstImage', '#secondImage']},
        {'#myImg2': ['#secondImage', '#firstImage']},
        {'#myImg3': ['...', '...']} // keep adding new items as object here
    ],
    $windowScrollTop = $(window).scrollTop(); // cache window scroll function

// loop through the array here
$.each(arrs, function (idx, obj) { 
    for (id in obj) {
        var $el = $(id), // cache the target element here
            args = obj[id],
            img1 = args[0].toString(),
            img2 = args[1].toString();

        if ($windowScrollTop >= $el - 150 && $windowScrollTop <= $el + 150) {
            showBgOnTop(img1, img2);
        }

    }

});

答案 1 :(得分:0)

嗯,这实际上是一个jQuery函数。

你唯一可以做的就是使用

来减少代码
$(window).scrollTop()

作为变量:

var windowScrollTop = $(window).scrollTop();

剩下的部分是条件,你不能使用条件是变量。

答案 2 :(得分:0)

这个怎么样:

function show(image1id, image2id) {
  var target1 = $(image1id).offset().top;
  var target2 = $(image2id).offset().top;

  if (($(window).scrollTop() >= target2 - 150) &&
       $(window).scrollTop() <= target2 + 150)) {
    showBgOnTop(image1id, image2id);
  }
}

show('#firstImage','#secondImage');
show('#secondImage','#firstImage');