-1

ウィンドウの幅と高さ+ divの幅と高さを取得して、調整された幅を見つけようとしています。また、jquery を使用して div を絶対に配置しようとしていますが、コードが機能していません。以下にコードを示します。

CSS:

#inner {
  width: 500px; height: 300px;
  background: #ff0000;
}

jQuery:

$(document).ready(function() {

  var screenWidth = $(window).width();
  var screenHeight = $(window).height();

  var boxWidth = $("#inner").width();
  var boxHeight = $("#inner").height();

  var adjustedWidth = screenWidth - boxWidth;
  var adjustedHeight = screenHeight - boxHeight;

  $("#inner").css('position', 'absolute');
  $("#inner").css('top', adjustedWidth + 'px');
  $("#inner").css('left', adjustedHeight + 'px');

});

私のjQueryで何が間違っていますか? うまくいけば、私の説明は明確でした。

4

3 に答える 3

1

div を一番右下に揃えようとしている場合は、top ->adjustWidth と left ->adjustHeight を混同しています。

$("#inner").css('top', adjustedWidth + 'px');
$("#inner").css('left', adjustedHeight + 'px');

逆にする必要がある場合:

$("#inner").css('top', adjustedHeight + 'px');
$("#inner").css('left', adjustedWidth + 'px');

それとは別に、あなたのコードは動作しているように見えます。

また、CSS の幅や高さを変更する場合、「px」を追加する必要はありません。

于 2013-02-03T01:01:19.333 に答える
0

これにはJavaScriptを使用する必要はありません。物事を絶対的に配置する場合、使用できるのはそれだけではleftありtopません。代わりに、必要に応じてを使用できrightますbottom。たとえば、実行しているように見えるように右下隅に何かを配置するには、次のように使用できます。

#something {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 300px;
    height: 150px;
    background: red;
}

それを試してみてください。

于 2013-02-04T02:26:41.460 に答える
0

コードにコンポーネントのサイズの取得が含まれている場合 (特にページに画像がある場合)、すべての画像がダウンロードされる前に実行され、その後ページのサイズが変わる可能性があるため、loadハンドラーではなくハンドラーにコードを配置する必要があります。readyready

また、あなたtopleft交換する必要があります。

$(document).on('load', function() {

  var screenWidth = $(window).width();
  var screenHeight = $(window).height();

  var boxWidth = $("#inner").width();
  var boxHeight = $("#inner").height();

  var adjustedWidth = screenWidth - boxWidth;
  var adjustedHeight = screenHeight - boxHeight;

  $("#inner").css('position', 'absolute');
  $("#inner").css('top', adjustedHeight + 'px');
  $("#inner").css('left', adjustedWidth + 'px');

});
于 2013-02-04T02:34:08.333 に答える