私はdivを持っていて、一番下の位置を見つけたいと思っています。このように Div のトップ ポジションを見つけることができますが、ボトム ポジションを見つけるにはどうすればよいですか?
var top = $('#bottom').position().top;
return top;
私はdivを持っていて、一番下の位置を見つけたいと思っています。このように Div のトップ ポジションを見つけることができますが、ボトム ポジションを見つけるにはどうすればよいですか?
var top = $('#bottom').position().top;
return top;
外側の高さを上に追加すると、親要素を基準にして下になります。
var $el = $('#bottom'); //record the elem so you don't crawl the DOM everytime
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin
要素を絶対配置する場合、またはドキュメントに対して相対的に配置する場合は、代わりにオフセットを使用して評価する必要があります。
var bottom = $el.offset().top + $el.outerHeight(true);
trnelsonが指摘したように、これは常に 100% は機能しません。配置された要素にこの方法を使用するには、オフセットも考慮する必要があります。例については、次のコードを参照してください。
var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);
編集:このソリューションは元の回答にも含まれるようになりました。
受け入れられた答えは完全に正しくありません。position() 関数は親に対して相対的であるため、使用しないでください。グローバルポジショニングを行っている場合(ほとんどの場合?)、次のように外側の高さでオフセットトップのみを追加する必要があります:
var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);
これまでの答えはうまくいきます。パディングや境界線などを使わずに高さだけを使用したい場合。
パディング、境界線、およびマージンを考慮したい場合は、を使用する必要があります.outerHeight
。
var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
var bottom = $('#bottom').position().top + $('#bottom').height();
下部は、マージンやパディングが含まれないため、ではなくtop
+です。outerHeight
height
var $bot,
top,
bottom;
$bot = $('#bottom');
top = $bot.position().top;
bottom = top + $bot.outerHeight(true); //true is necessary to include the margins
var top = ($('#bottom').position().top) + ($('#bottom').height());