首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果我使用变量,为什么这个jQuery动画和附加不能工作?

如果我使用变量,为什么这个jQuery动画和附加不能工作?
EN

Stack Overflow用户
提问于 2013-08-23 11:42:42
回答 1查看 114关注 0票数 0

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

然而,这似乎行不通。我怎么才能修好?

这是我的密码。

代码语言:javascript
运行
复制
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);
    }
}

原始代码

代码语言:javascript
运行
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-23 11:46:03

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

代码语言:javascript
运行
复制
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);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18402007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档