0

我正在尝试获取宽度div.newsticker 并尝试将其用作动画和附加中的变量。

但是,这似乎不起作用。我该如何解决?

这是我的代码。

jQuery(document).ready(function () {
    var width = jQuery("div.newsticker").width()+"px";
}); 

// To get resize notification
jQuery(window).on("resize", function() {
   var width = jQuery(".newticker").width()+"px";
});

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}

原始代码

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":"400px","opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:400px;opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}
4

1 回答 1

1

您需要使用正确的范围声明变量。

var width = '';

jQuery(document).ready(function () {
    width = jQuery("div.newsticker").width()+"px";
}); 

// To get resize notification
jQuery(window).on("resize", function() {
   width = jQuery(".newsticker").width()+"px";
});

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}
于 2013-08-23T11:46:03.223 回答