2017-06-06 332 views
0

我得到“各”:遗漏的类型错误:在animateIfInview 在atonscroll遗漏的类型错误:无法读取属性未定义

和继承人无法读取属性未定义 “每个”代码:

<script> 
function animateIfInView() { 
$.each($("content-img"), function(key, value) { 
if (isElementInViewport($(value))) { 
$(value).addClass("content-img-in-view"); 
} else { 
    // (Optional) Fade out when out of view 
    $(value).removeClass("content-img-in-view"); 
    } 
    }); 
    } 

    // http://stackoverflow.com/a/7557433/5628 
    function isElementInViewport(el) { 
    //special bonus for those using jQuery 
    if (typeof jQuery === "function" && el instanceof jQuery) { 
    el = el[0]; 
    } 

    var rect = el.getBoundingClientRect(); 

    return (
    rect.top >= 0 && 
    rect.left >= 0 && 
    rect.bottom <= 
    (window.innerHeight || 
    document.documentElement.clientHeight) /*or $(window).height() */ && 
    rect.right <= 
    (window.innerWidth || 
    document.documentElement.clientWidth) /*or $(window).width() */ 
); 
    } 
    </script> 

我该如何解决这个错误?我在代码中缺少什么?谢谢你们提前

+0

此:'$( “内容IMG”)'是不正确的选择。这是一个ID还是一个类? – Twisty

+0

我也建议使用'$(“。content-img”)。each();' – Twisty

+0

它为一个类,因此该页上的每个图像在滚动事物上都会淡入淡出 – nellement

回答

0

我建议如下:

function animateIfInView() { 
    $(".content-img").each(function(key, elem) { 
    if (isElementInViewport($(elem))) { 
     $(elem).toggleClass("content-img-in-view"); 
    } 
    }); 
} 

类选择使用$(".className"),你的代码中缺少它的.。另外,如果使用元素,建议使用.each()$.each()这是数组和对象的建议。

+0

谢谢,我会尝试当我上班的电脑,会让你知道和投票,如果它工作 – nellement

+0

由于某种原因没有什么变化:(不知道为什么 – nellement

+0

你的代码应该工作,只要你使用正确的选择器:'.content-img' – Twisty

0
jQuery.each(array/object,callback_function); 

需要第一个参数作为数组或对象。阅读文档 here。我建议使用var obj = $(document).find(".content-img");然后使用 作为

$.each(obj,function(key,value){ 
//your code goes here 
}); 
+0

你能告诉我更多什么代码广告在我的原始帖子顶部,使这项工作?提前致谢 – nellement

相关问题