如何使用$(this)将'top'css值设置为变量

时间:2011-07-06 05:55:24

标签: javascript jquery variables

如何使用$(this)将'top'css值设置为变量?

到目前为止,我还没有能够使用此代码:

    $("#thumb").click(function () {

        var TopV = $(this).css('top');
        alert(TopV)
    });

3 个答案:

答案 0 :(得分:4)

该代码段正在尝试读取CSS“top”属性,而不是写入它。它可能在大多数元素上都不存在。

你的意思是你想把它设置为某种值,就像这样吗?

$(this).css('top', '5px');

More info on the css method

你还应该知道'top'属性只有在它设置的元素没有'静态'定位时才有意义 - 也就是说,如果它具有绝对,相对或固定。否则它会被忽略:它不会做任何事情,也可能无法读取。

More info on the top CSS property

答案 1 :(得分:1)

你想把它设置为什么?这样的事情会做到:

   $("#thumb").click(function () {
        var targetTop = '100px';
        $(this).css('top', targetTop);
        var TopV = $(this).css('top');
        alert(TopV)
    });

答案 2 :(得分:1)

var offset = $(this).offset();
$(this).html( "top: " + offset.top );

您也可以尝试position()