>  기사  >  웹 프론트엔드  >  자바스크립트 버퍼모션 구현 방법(예시 2개)_javascript 스킬

자바스크립트 버퍼모션 구현 방법(예시 2개)_javascript 스킬

WBOY
WBOY원래의
2016-05-16 15:21:071186검색

본 글의 예시에서는 자바스크립트 버퍼 모션 구현 방법을 설명합니다. 참고하실 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

구현 원리: (목표 거리 - 현재 거리) / 기준 = 속도(거리가 멀수록 속도는 작아지며, 거리와 속도는 반비례)

코드 복사 코드는 다음과 같습니다.
(500 - oDiv.offsetLeft) / 7 = iSpeed;

참고: : 계산된 속도에 소수점이 포함된 경우 반올림해야 합니다.

코드 복사 코드는 다음과 같습니다.
(500 - oDiv.offsetLeft) / 7 = iSpeed ​​​​= iSpeed>0? Math.ceil(iSpeed):Math.floor(iSpeed);

예시 1: 슬라이더 버퍼 이동

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>缓冲运动</title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute; top:50px; left:0;}
span{ width:1px; height:300px; background:black; position:absolute; left:300px; top:0; display:block;}
</style>
<script>
window.onload = function()
{
 var oBtn = document.getElementById('btn1');
 var oDiv = document.getElementById('div1');
 oBtn.onclick = function()
 {
  startMove(oDiv, 300);
 };
};
var timer = null;
function startMove(obj, iTarget)
{
 clearInterval(timer);
 timer = setInterval(function(){
  var iSpeed = (iTarget - obj.offsetLeft)/8;
  iSpeed = iSpeed>0&#63;Math.ceil(iSpeed):Math.floor(iSpeed);
  if(iTarget==obj.offsetLeft){
   clearInterval(timer);
  }else{
   obj.style.left = obj.offsetLeft + iSpeed + 'px';
  }
 }, 30);
}
</script>
</head>
<body>
<input id="btn1" type="button" value="移动" />
<div id="div1"></div>
<span></span>
</body>
</html>

예 2: 사이드바 슬라이딩

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>侧边栏滑动</title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute; right:0; top:0;}
</style>
<script>
window.onload = window.onscroll = function()
{
 var oDiv = document.getElementById('div1');
 var iScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
 var clientHeight = document.documentElement.clientHeight;
 var iH = (clientHeight - oDiv.offsetHeight)/2 + iScrollTop;
 //oDiv.style.top = iH + 'px';
 startMove(oDiv, parseInt(iH));
};
var timer = null;
function startMove(obj, iTarget)
{
 clearInterval(timer);
 timer = setInterval(function(){
  var iSpeed = (iTarget - obj.offsetTop) / 8;
  iSpeed = iSpeed>0&#63;Math.ceil(iSpeed):Math.floor(iSpeed);
  if(obj.offsetTop == iTarget){
   clearInterval(timer);
  }else{
   obj.style.top = obj.offsetTop + iSpeed + 'px';
  }
 }, 30);
}
</script>
</head>
<body style="height:2000px;">
<div id="div1"></div>
</body>
</html>

JavaScript 모션 효과와 관련된 더 많은 콘텐츠를 보려면 이 사이트의 특별 주제인 " JavaScript 모션 효과 및 기술 요약"

을 참조하세요.

이 기사가 JavaScript 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.