如何使用jQuery设置最高位置


67

我正在创建自定义div滚动条,并希望设置内容div的顶部位置。我的jQuery代码如下:

containerOuterHeight=$("#messagePopUpContainer").outerHeight();
            contentOuterHeight=$("#content").outerHeight();
            contentTopPosition=$("#content").offset().top;
            alert("contentTopPosition"+contentTopPosition);
            alert(contentTopPosition-(containerOuterHeight/20));
            $("#content").offset().top=contentTopPosition-(containerOuterHeight/20);
            //$("#content").css("top",( contentTopPosition-(containerOuterHeight/20) ) + "px");
            alert("contentTopPosition"+$("#content").offset().top);
            //alert("Fontsize"+$('#content').css('font-size') );

和html是:

<div id='messagePopUpContainer' style='background-color:#ffffff; overflow: hidden;'>
<a href='javascript:void(0);' id='popupanchor' onkeydown='PopupKeyHandler("' + elmId + '");'></a>

<div id='content' style='width:350px'>' + methods.settings[elmId].text + '</div >
<div id='popupReturn'>Return</div></div></div>'

试试$(element).position() $(element).position().top$(element).position().left
KingRider

Answers:



66

使用.css()可以很容易地访问CSS属性并进行操作。例如,要更改单个属性:

$("selector").css('top', '50px');

14

你也可以

   var x = $('#element').height();   // or any changing value

   $('selector').css({'top' : x + 'px'});

要么

您可以直接使用

$('#element').css( "height" )

.css( "height" )和之间的区别在于,.height()后者返回一个无单位像素值(例如400),而前者返回一个完整单位的值(例如400px)。当需要在数学计算中使用元素的高度时,建议使用.height()方法。jQuery文档


5

仅供参考,如果您正在使用:

 $(el).offset().top 

要获得位置,它可能会受到父元素位置的影响。因此,您可能需要保持一致,并使用以下内容进行设置:

$(el).offset({top: pos});

与上面的CSS方法相反。


感谢您添加此内容。
ow3n19'2

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.