将动画从特定位置滚动到另一个位置

时间:2016-05-24 01:10:59

标签: javascript jquery scroll translate

假设我有一个方框,并且tranform:translateX(-200px) offset to the left

偏离了正确的位置

下面的示例pic有两个<section>,一个是大灰框,另一个是红色的.box。该插图显示了动画应该在观看者滚动并且有争议地从.box来回移动-200px0px时移动的位置/方式。

user controls the <code>.box</code>

$( document ).ready(function(){

  $(window).scroll(function(){

    var wScroll = $(this).scrollTop();
    var greySection = $('.grey').height(); // Which is 800px high
  
    // (what other variables, and functions could I add? )
  
    if( wScroll > greySection /1.3 ) // 1.3 of section.grey is where i want the animation to start 
      $('.box').css('transform','translateX(' + /* (what do i put here?) */ + 'px)');
  
    });
  
});
.grey{  /* for visual purposes */
  background-color: grey;
}

section {
  width:100%;
  height:800px;
}

p{
  width:100%;
  text-align:center;
}

.box{
  width:200px;
  height:200px;
  background-color:red;
  margin:0 auto; /* Here is where the box position should end up */
  transform:translateX(-200px); /* Control this property to move box */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<section class="grey">
  <p>Some contents here. Ignore this section</p>
</section>

<section id="box-holder">
  <div class="box"></div>
</section>

我怎样才能让用户仅使用滚动条来回控制框位置的transform属性到完成的地点-200px0px

3 个答案:

答案 0 :(得分:1)

我现在要研究一下,但先是几点提示。

准备好文档,这样你的变量就会被存储,而不是在每次滚动之后。

$( document ).ready(function() {
 var greySection = $('.grey').height(); 
});

盒子是否应该向右滑动,直接在中间或向右滑动200px?我对-200px感到有些困惑。

答案 1 :(得分:0)

你去了 https://jsfiddle.net/DenizTemizer/j6m73qnf/1/

var greySection;
$( document ).ready(function() {
  greySection = $('.grey').height();
  console.log(greySection);
});

$(window).scroll(function() {
  var wScroll = $(this).scrollTop();
  if( !$('.grey').hasClass('animated') && wScroll > (greySection / 1.3) ) {
    console.log("animate");
    $('.grey').addClass('animated');
    $('.box').css({
      "-webkit-transform":"translateX(0)",
      "-ms-transform":"translateX(0)",
      "transform":"translateX(0)"
    });
  }
});

添加为新答案,以便更容易找到此线程是否变大。

答案 2 :(得分:0)

从我正在处理的东西中撕掉这些东西,然后将它们整合在一起,挖掘。

您想要的公式如下:

(scrollTop-topOffset)/(pageHeight-windowHeight-topOffset)*translateDistance

这就是JavaScript中的地方:

mem[7] = -(~~(((mem[0]-BoxOffset)/mem[6])*BoxDistance));

这需要一些工作,我使用右移零来舍入结果,但是当我运行片段时它表现得很奇怪,所以我使用了双&#39; ~~&#39;然后不得不把它设置为否定的 - &#39; - &#39;为了使它积极,不要复制/粘贴,修复/整理我的鸡肉划痕! XD

&#13;
&#13;
INP=0xFFFF; // INPut flags
BoxDistance=200; // box travel distance
mem=[]; // mem array


JC = function(intv, event){


	L_BOOT:{


	L_TRIPEVENT:{


	if (!event) break L_TRIPEVENT;		// if there is an event

		event = event || window.event;	// for IE
		if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; }	// stop bubble up
		FP= event.target ? event.target : event.srcElement;	// get it

	if ((INP&=intv)&0x002) break L_TRIPEVENT;	// if boot is complete


		INP_Resize:{

			// Save the old browser width/height dimentions? if needed ...

		if(INP&0x020) break INP_Resize; INP |= 0x020; // INP_Resize = OFF

			//
			// Get the window dimentions
			//
			mem[2] = (document.body.innerWidth)? document.body.innerWidth : document.body.clientWidth;		// window width
			mem[3] = (document.body.innerHeight)? document.body.innerHeight : document.body.clientHeight;	// window height


			//
			// Get the page dimentions
			//
			mem[4]=document.getElementById('box-holder').offsetWidth;		// section width:
			mem[5]=document.getElementById('box-holder').offsetHeight*2;		// section width: (box-holder x 2) both sections are of the same height
			BoxOffset=document.getElementById('ThisTrigger').offsetHeight;		// section width:			


			mem[6]=mem[5]-mem[3]-BoxOffset;	//  page height - window height = (scroll bottom)


		}// INP_Resize:


		INP_Scroll:{

			mem[1] = mem[0];		// Save last scroll location, not really needed ... 

		if(INP&0x010) break INP_Scroll; INP |= 0x010; // INP_Scroll = OFF

			mem[0] = ((document.body.scrollTop)? (document.body.scrollTop) : ((document.documentElement.scrollTop)? (document.documentElement.scrollTop):(window.pageYOffset) ));// get current scroll location

			if ( BoxOffset<mem[0] ) { // get current scroll location

				if (BoxOffset<mem[0]) {

					mem[7] = -(~~(((mem[0]-BoxOffset)/mem[6])*BoxDistance)); // right shift 0 times, un-round to a whole number

					/*
					mem[0] = scroll top -> DistanceThusFar
					BoxOffset = with the top offfset
					mem[6] = (scroll bottom) -> DistanceCanGo
					BoxDistance = distance

					(DistanceThusFar / DistanceCanGo) = (0.???)%
						the ratio between how far, and whats left to go
					(0.???) * (BoxDistance) = (???px)
						the ratio multiplied by BoxDistance is the distance
					*/

					mem[7] = BoxDistance<mem[7] ? BoxDistance : mem[7];	// if the number rounded, exceeds BoxDistance, set it to BoxDistance

				}//if (mem[0]>=BoxOffse...

			} else {

				mem[7]^=mem[7]; // if the number rounded, is greater than 0, when scrollTop is less then trigger height, set it to zero

			}

			AX=mem[7];

			document.getElementById("meee").setAttribute('style', 'margin-left: '+AX+'px;'); // update box distance

		}// INP_Scroll:


	}//L_TRIPEVENT:

	if (INP&0x001) break L_BOOT; INP|=0x001; INP&=0xFFD; // L_BOOT = OFF

		INP &= 0xFEF; // 1110:1111 <- set this bit off, to trip SCROLL interupt
		INP &= 0xFDF; // 1110:1111 <- set this bit off, to trip SCROLL interupt

	}//L_BOOT:
	

		//
		// Print out memory
		//
		PrintText='';
		i=0;
		do{
			PrintText += "<br> " + i + "	" + mem[i];
		i++;
		}while (i^0x08)
		document.getElementById("JC_TEST_TEXT").innerHTML = PrintText;
		PrintText^=PrintText;


TIC=setTimeout(JC,100);
}; JC();


function JCinterupts(i0,i1,i2,i3){

    if ('addEventListener' in window){
		window.addEventListener(i0, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFBF ), false);
        window.addEventListener(i1, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFEF ), false);
        window.addEventListener(i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFDF ), false);
        window.addEventListener(i3, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFFE ), false);
    } else if ('attachEvent' in window){//IE
        window.attachEvent('on'+i0, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFBF ) );
        window.attachEvent('on'+i1, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFEF ) );
        window.attachEvent('on'+i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFDF ) );
        window.attachEvent('on'+i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFFE ) );
    }
    
} JCinterupts('click','scroll','resize','load');
&#13;
<!--

░░█████░░░░░░░░░░░░███░░░░░░░░░░░░
░░░░█░░░░░░░░░░░░░░█░░░░░░░░░█░░░░
░░░░█░░███░███░███░█░░░███░░░█░███
░░░░█░░█░█░█░█░█░░░█░░░█░█░███░█░█  JonathanClingan
░░░░█░░█░█░█░█░░░█░█░░░█░█░█░█░█░░  ©JonsCode
░░███░░███░█░█░███░███░███░███░███  5.24.16

  ■ JonWasHere :P

-->

<HTML /><!-- HTML markup -->
<HEAD /><!-- self closing tags -->

  <style>

    HTML,BODY {
      margin:0;
      padding:0;
      border:0;
    }
    .grey{  /* for visual purposes */
      background-color: grey;
    }
    .darkgrey{  /* for visual purposes */
      background-color: darkgrey;
      height:34px;
    }
    section {
      width:100%;
      height:134px;
    }

    p{
      width:100%;
      text-align:center;
    }
    .box{
      left:200px;
      width:200px;
      height:200px;
      background-color:red;
      margin:0 auto;
    }
    #JC_TEST_HOLD{
      position:absolute;
      position:fixed;
      overflow:visible;
      padding:0 10px 0 0;
      color:white;
      z-index:900;
      text-align:left;
    }
    #JC_TEST_BOX{
      height:100%;
      overflow:auto;
      position:relative;
      margin:0;
      padding:0 15px 0 0;
      color:white;
      background:rgba(0,0,0,0.8);
      text-align:left;
    }
    #JC_TEST_TEXT{
      text-align:left;
    }

  </style>

<BODY /><!-- Mhmmm, I like yo' body. ;) -->

  <DIV ID="JC_TEST_HOLD" >
    <DIV ID="JC_TEST_BOX" >
      <p id="JC_TEST_TEXT"></p>
    </DIV>
  </DIV>

  <section id="ThisBox" class="grey">
    <div id="ThisTrigger" class="darkgrey">
      <p>Some contents here. Ignore this section, or pay attention.</p>
    </div>
  </section>

  <section id="box-holder">
    <div id="meee" class="box"></div>
  </section>
&#13;
&#13;
&#13;