>  기사  >  웹 프론트엔드  >  JS는 우수한 호환성_javascript 기술로 화면 기반 스크롤 효과를 구현합니다.

JS는 우수한 호환성_javascript 기술로 화면 기반 스크롤 효과를 구현합니다.

WBOY
WBOY원래의
2016-05-16 15:33:25974검색

이 기사의 예에서는 호환성이 좋은 화면 기반 스크롤 효과의 JS 구현을 설명합니다. 참고하실 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

코드의 매개변수에 대한 설명은 다음과 같습니다.

id 스크롤하려는 콘텐츠의 ID
l 가로좌표의 위치가 오른쪽에 가깝게 쓰여있지 않습니다
t 페이지에 배치하려는 위치는 기본적으로 아래쪽 가장자리를 의미합니다.
f 1은 고정, 기록되지 않음을 의미하거나 0은 롤링을 의미합니다.

이 코드는 스크롤할 때 흔들리지 않으며 화면 크기에 따라 변경됩니다

런닝 효과 스크린샷은 다음과 같습니다.

온라인 데모 주소는 다음과 같습니다.

http://demo.jb51.net/js/2015/js-scroll-follow-src-style-codes/

구체적인 코드는 다음과 같습니다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>随屏滚动</title>
<style>
 html,body{
  padding:0;
  margin:0;
 }
</style>
</head>
<body>
 <div id="aa" style="width:200px;height:200px;background:#c0c0c0;" >我在随屏滚</div>
 <div id="bb" style="width:200px;height:200px;background:#c0c0c0;" >我静止不动</div>
 <div style="width:100%;height:500px;background:#000"></div>
 <div style="width:100%;height:500px;background:green"></div>
 <div style="width:100%;height:500px;background:red"></div>
</body>
</html>
<script>
function scroll(p){
 var d = document,dd = d.documentElement,db = d.body,w = window,o = d.getElementById(p.id),ie = /msie/i.test(navigator.userAgent),style;
  if(o){
  o.style.cssText +=";position:"+(p.f&&!ie&#63;'fixed':'absolute')+";"+(p.l==undefined&#63;'right:0;':'left:'+p.l+'px;')+(p.t!=undefined&#63;'top:'+p.t+'px':'bottom:0');
   if(p.f&&ie){
   o.style.cssText +=';left:expression(body.scrollLeft + '+(p.l==undefined&#63;db.clientWidth-o.offsetWidth:p.l)+' + "px");top:expression(body.scrollTop +'+(p.t==undefined&#63;db.clientHeight-o.offsetHeight:p.t)+'+ "px" );'
    db.style.cssText +=";background-image:url(about:blank);background-attachment:fixed;"
   }else{
    if(!p.f){
     w.onresize = w.onscroll = function(){
      var timer,timer1;
      return function(){
       if(timer)
        clearTimeout(timer);
       timer = setTimeout(function(){
        timer1 = setInterval(function(){
         var st = db.scrollTop,c;
         c = st - o.offsetTop + (p.t!=undefined&#63;p.t:(w.innerHeight||db.clientHeight)-o.offsetHeight);
         if(c!=0){
          o.style.top = o.offsetTop + Math.ceil(Math.abs(c)/10)*(c<0&#63;-1:1) + 'px';
         }else{
          clearInterval(timer1);  
         }
        },10)
       },100)//控制滚动的频率越大频率越慢
      }
     }()
    }
   }
  } 
 }
 scroll({
  id:'aa'
 })
  scroll({
  id:'bb',
  l:0,
  t:200,
  f:1
  })
</script>

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

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