【问题标题】:jquery animate variable from bound function来自绑定函数的jquery动画变量
【发布时间】:2011-11-29 21:22:06
【问题描述】:

http://jsfiddle.net/motocomdigital/c8Mey/1/

我正在使用一个 twitter 脚本,一旦加载了推文,我将绑定一个函数来获取 div#tweet 的动态高度。

但之后我需要将该变量传递给 .animate 脚本 - 这就是我目前所得到的。

    $("#tweet").tweet({
        count: 1,
        username: ["motocomdigital"],
        loading_text: "searching twitter...",
        intro_text: null,
        outro_text: null
    }).bind("loaded", function(){

        // this binded function is getting the height of tweet div once loaded...
        var tweetHeight = $("#tweet").height();

    });

然后我需要将变量 tweetHeight 传递到我在下面运行的动画脚本中。我认为很简单,但我认为我的编码有点错误。

    $latestTweet.hover(function() {
        // see variable in this is first alternation
        $latestTweet.stop().animate({ top: "-" + tweetHeight + "px", width: "512px", 
    }, function() {
        $latestTweet.stop().animate({ top: "-1px", width: "334px", backgroundColor: "#464848" }, 300);
    });

假设 div#tweet 高度(一旦加载 twitter 内容)是 200px,我需要这个变量的结果是......

$latestTweet.stop().animate({ top: "-200px", width: "512px",

谁能帮我理解如何正确编写这个 - 我什至尝试将我的动画脚本放在绑定函数中,但它仍然没有传递变量。

重大更新

我刚刚弄清楚为什么它给出了错误的 #tweet div 高度!这是因为我的#tweet div 有顶部和底部填充,而 .height 在创建 tweetHeight 变量时不包括这些尺寸,请参阅jsfiddle here

有谁知道如何将固定像素尺寸添加到我的 tweetHeight 变量中?例如额外的 50px?

我将它绑定到 twitter javascript 的原因也是因为 #tweet div 的高度是动态的,因此从顶部位置开始的动画总是需要 #tweet div 的最终高度来定位它完美。请参阅jsfiddle here 的简化演示。

【问题讨论】:

    标签: javascript jquery variables jquery-animate


    【解决方案1】:

    你只需要在函数外创建一个变量:

    var tweetHeight = 200; // a default height
    // here come's the $.tweet() code, and you should only assign the new value to the "tweetHeight" variable
    
    //$latestTweet.stop().animate({ top: -tweetHeight ...
    

    更新至上述“主要更新”

    如果您使用函数设置变量值,则可以操纵这些额外的像素:

    var tweetHeight = 200;
    function setTweetHeight(h) {
        tweetHeight = h + 50;
    }
    

    现在使用函数来分配新值:

    setTweetHeight( $('#tweet').height() ); // example
    

    【讨论】:

    • 啊,是的,但这条推文是动态的,我在做 jsfiddle 时确实发现了我的问题——它检索 div 的高度不包括我的填充——你现在怎么办在我的 tweetHeight 变量上添加我的顶部和底部填充尺寸?谢谢http://jsfiddle.net/motocomdigital/c8Mey/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多