3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascript - stickyみたいにfixedを使いたいけど使えない場合の実装

Posted at

下記場合

sample.html
<!DOCTYPE html>
<html>
  <head>
    <title>sample</title>
  </head>
  <body style='overflow: hidden;'>
    <div style='width: 500px; height: 500px; overflow-x: scroll; overflow-y: scroll; margin: 30px auto;'>
      <div style='width: 300px; height: 1000px; background-color: rgb( 0, 0, 255 )'>
        この属性の特徴:縦に長い・青の背景色
        固定にするよ!
      </div>
      <div style='width: 1000px; height: 300px; background-color: rgb( 255, 0, 0 )'>
        この属性の特徴:横に長い・赤の背景色
        固定にするよ!
      </div>
      <div stype='width: 700px; height: 700px; margin: 300px 0px 0px 300px; background-color: rgb( 0, 255, 0 );'>
        この属性の特徴:横にも縦にも長い・緑の背景色
      </div>
    </div>
  </body>
</html>

なにがしたいのか

 「横スクロール時は、赤と緑が動くようにして青を固定!」
 「縦スクロール時は、青と緑が動くようにして赤を固定!」

以下をつかえ!

sample.js
/*
 * -----------------
 * reference arguments
 * 	element selector name -> as method '$' to the library 'jquery' set argument. return null = throw error
 *  toggle -> a String 'top' or 'left'. this is set you. top: element is deal vertical scrolling. left: element is deal horizon scrolling.
 */
function scrolling( parents_element_selector, target_element_selector, toggle, default_margin_value ) {
	
	if( !toggle || ( toggle !== 'top' && toggle !== 'left' ) ) {
		return;
	}
	if( !target_element_selector || !( $( target_element_selector ) ) ) {
		return;
	}
	
	// how much to user scrolled length.
	// scrolled length value + element margin value before element was scrolled by user
	var aflterScrolledValue = 0;
	if( toggle === 'top' ) {
		afterScrolledValue = document.getElementById(parents_element_selector).scrollTop;
	} else {
		afterScrolledValue = document.getElementById(parents_element_selector).scrollLeft;
	}
	
	// set value as look liked to scrolling element
	$(target_element_selector).css( 'margin-' + toggle, (afterScrolledValue + default_margin_value) + 'px' );
}

もうちょっと丁寧にまとめるから待ってて。。。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?