javascript - 写jq插件时遇到问题
高洛峰
高洛峰 2017-04-10 17:46:01
[JavaScript讨论组]

Uncaught TypeError: Cannot use 'in' operator to search for 'marginTop' in undefined
这个提示是什么意思?
我写的插件包含一个动画效果marginTop,但是却不能设置,为什么

//代码

(function($){

$.fn.newsScroll = function(options){
    var dft = {
        'speed': '600',  //滚动速度
        'time' : '3000'  //每次滚动的时间
    };
    var opts = $.extend(dft, options);
    var setTime;
    var scrollSpeed = opts.speed;
    var scrollTime = opts.titme;
    function newsScroll(){
        var newsHeight = $(this).children().eq(0).height();  //获取父元素第一个子元素的高度,为父元素向上移动做准备;
        $(this).animate({ "marginTop": -newsHeight + "px"}, scrollSpeed, function() {
            $(this).css("marginTop", "0").children().eq(0).appendTo($(this));  //设置上边距为零,为了下一次移动做准备
        });
    }
    $(this).hover(
        function () {
            clearInterval(setTime);
        },
        function(){
            setTime = setInterval(newsScroll,scrollTime);
        }
    ).trigger("mouseleave");
}
})(jQuery)
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
高洛峰

newscroll的指向是window。你可以输出this看看

PHP中文网

你的newScroll中的this指向不再和$.fn.newsScroll = function(options){}中的this指向相同。

var that = this;
function newsScroll(){
        var newsHeight = $(that).children().eq(0).height();  //获取父元素第一个子元素的高度,为父元素向上移动做准备;
        $(that).animate({ "marginTop": -newsHeight + "px"}, scrollSpeed, function() {
            $(that).css("marginTop", "0").children().eq(0).appendTo($(that));  //设置上边距为零,为了下一次移动做准备
        });
    }
高洛峰

newsScroll中this的指向改变了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号