1

これが私のウェブサイトで見たいものです。本体の幅と3つの列(20%、70%、10%)のテーブル。ブラウザウィンドウのサイズが変更されると、テーブルのサイズも変更され、テーブルの列のサイズもそれぞれ変更されます。

左側の列(幅20%の列)にはDIV要素が含まれており、テキストが含まれています。

<body style="width:100%;">
 <table style="width:100%;">
  <tr>
   <td style="width:20%">
    <div style="position:relative;">
     Here goes some text.  This is a lot of text and usually should wrap around inside of the DIV element.
    </div>
    ...
  </tr>
 </table>
</body>

これはすべて問題なく機能し、ラッピングもすべてです。これで、ユーザーがページを下にスクロールすると、DIV要素とそのコンテンツが上にスクロールしてウィンドウの外に出ます。

私がやりたいのは、DIVが表示領域を離れる前に、ブラウザの上部にDIVを「修正」することです。ユーザーが再び上にスクロールすると、DIVはブラウザーの上部から切り離され、通常の位置に戻ります。最終的な効果は、DIVが表示領域の内側をスクロールするか、そうでない場合はブラウザの上部にアタッチすることです。onscrollこれは、イベントにアタッチした単純なJavascriptコールバックを使用して実装されます。これにより、fixedとの間の位置が変更されrelativeます。うまく動作します。

今私が気付いたのは、DIVの幅が変わることだけです!スクロールする限り、またDIVの位置がである限り、親TDの幅に等しくなりrelativeます。Javascriptコールバックが位置をfixed DIVの幅に変更した瞬間、変更されて隣接するテーブル列にオーバーフローします。

DIVの寸法を含めるにはどうすればよいですか?

ありがとう :)

4

2 に答える 2

1

Thanks @abelito for the hint :) Turns out that the solution is a little easier than this. I do need to change the width of the DIV element when I change its position, but since the TD has a 20% width, all I have to do is to toggle the width of the DIV between 20% and 100% depending on its position value. Here is the Javascript which works:

var div_is_sticky = false;

window.onscroll = function() {
  var y = window.scrollY;
  if (y >= 250) {
    if (div_is_sticky) {
      // Do nothing.
    }
    else {
      var div = document.getElementById("submenudiv");

      div.style.position = "fixed";
      div.style.width = "20%";

      div_is_sticky = true;
    }
  }
  else if (y < 250) {
    if (div_is_sticky) {
      var div = document.getElementById("submenudiv");

      div.style.position = "relative";
      div.style.width = "100%";

      div_is_sticky = false;
    }
    else {
      // Do nothing.
    }
  }
}

Thanks!

于 2012-12-03T02:26:42.697 に答える
0

位置が固定に変更されたら、DIV の幅も制御する必要があるようです。生の JavaScript を使用している場合は、element.style.width を親の element.offsetWidth + 'px' に変更してみてください。jquery を使用している場合は、.width() メソッドを使用する必要があります。リンク:

https://developer.mozilla.org/en-US/docs/DOM/element.offsetWidth

http://api.jquery.com/width/

ユーザーが下にスクロールした場合は、幅を「100%」に戻すことを忘れないでください。

于 2012-12-03T02:07:51.010 に答える