기초공사 (html,css,javascript)

js_top버튼이 visible로 바꿔지고 위로 올라감 본문

카테고리 없음

js_top버튼이 visible로 바꿔지고 위로 올라감

에스프레소라떼 2023. 1. 10. 22:05

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript for Web Designers - Back to top button demo</title>

        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Cormorant+Infant:700,700italic|Lato:400,400italic,700">
        <link rel="stylesheet" href="1112_style.css">
    </head>
    <body>
        <header id="top">
            <h1>Moby Dick</h1>
            <h2>by Herman Melville</h2>
        </header>

        <main>
            <p>Presently a breeze sprang up; Stubb feigned to cast off from the whale; hoisting his boats, the Frenchman soon increased his distance, while the Pequod slid in between him and Stubb's whale. Whereupon Stubb quickly pulled to the floating body, and hailing the Pequod to give notice of his intentions, at once proceeded to reap the fruit of his unrighteous cunning. Seizing his sharp boat-spade, he commenced an excavation in the body, a little behind the side fin. You would almost have thought he was digging a cellar there in the sea; and when at length his spade struck against the gaunt ribs, it was like turning up old Roman tiles and pottery buried in fat English loam. His boat's crew were all in high excitement, eagerly helping their chief, and looking as anxious as gold-hunters.</p>

            <p>And all the time numberless fowls were diving, and ducking, and screaming, and yelling, and fighting around them. Stubb was beginning to look disappointed, especially as the horrible nosegay increased, when suddenly from out the very heart of this plague, there stole a faint stream of perfume, which flowed through the tide of bad smells without being absorbed by it, as one river will flow into and then along with another, without at all blending with it for a time.</p>

            <p>"I have it, I have it," cried Stubb, with delight, striking something in the subterranean regions, "a purse! a purse!"</p>

            <p>Dropping his spade, he thrust both hands in, and drew out handfuls of something that looked like ripe Windsor soap, or rich mottled old cheese; very unctuous and savory withal. You might easily dent it with your thumb; it is of a hue between yellow and ash colour. And this, good friends, is ambergris, worth a gold guinea an ounce to any druggist. Some six handfuls were obtained; but more was unavoidably lost in the sea, and still more, perhaps, might have been secured were it not for impatient Ahab's loud command to Stubb to desist, and come on board, else the ship would bid them good bye.</p>

            <p>Now this ambergris is a very curious substance, and so important as an article of commerce, that in 1791 a certain Nantucket-born Captain Coffin was examined at the bar of the English House of Commons on that subject. For at that time, and indeed until a comparatively late day, the precise origin of ambergris remained, like amber itself, a problem to the learned. Though the word ambergris is but the French compound for grey amber, yet the two substances are quite distinct. For amber, though at times found on the sea-coast, is also dug up in some far inland soils, whereas ambergris is never found except upon the sea. Besides, amber is a hard, transparent, brittle, odorless substance, used for mouth-pieces to pipes, for beads and ornaments; but ambergris is soft, waxy, and so highly fragrant and spicy, that it is largely used in perfumery, in pastiles, precious candles, hair-powders, and pomatum. The Turks use it in cooking, and also carry it to Mecca, for the same purpose that frankincense is carried to St. Peter's in Rome. Some wine merchants drop a few grains into claret, to flavor it.</p>

            <p>Who would think, then, that such fine ladies and gentlemen should regale themselves with an essence found in the inglorious bowels of a sick whale! Yet so it is. By some, ambergris is supposed to be the cause, and by others the effect, of the dyspepsia in the whale. How to cure such a dyspepsia it were hard to say, unless by administering three or four boat loads of Brandreth's pills, and then running out of harm's way, as laborers do in blasting rocks.</p>
        </main>

        <footer>
            <p><small><em>Typography and color scheme based on <a href="http://typespiration.com/design/the-signal/">"The Signal"</a>.</em></small></p>
            <a id="back-to-top" href="#">Top</a>
        </footer>

<script>
/*
 * - 변수 지정하기  
 변수명btt  id back to top
 * - 문서의 높이를 계산하고 원하는 부분이 상단에서 얼마큼 떨어져 있는지 offset 값을 계산하기
 * - 스크롤과 클릭 이벤트 작성하기
 */ 
var btt = document.getElementById('back-to-top'),
docElem = document.documentElement, //html document의 높이자체를 표현 브라우저마다 높이 다르다.
offset,
scrollPos,//(스클로양)
docHeight;

// 문서높이 계산하기
//문서자체의높이 구해보는것 여러가지
//scrollHeight / offsetHeight 두개 같다.==>브라우저마다 높이 다르다.
//docHeight = docElem.scrollHeight; //scrollHeight 브라우저의 문서자체의 높이 700나왔고
//docHeight = docElem.offsetHeight; 높이가 800이나왔다. 둘중어느것을 써야하는가?
//콘솔창에 Math.max,(100,800);입력하면 800나오고 / Math.min(100,800)입력하면100이 나온다. 이거 활용 아래
docHeight = Math.max(docElem.offsetHeight,docElem.scrollHeight); 

if(docHeight != 'undefined'){
  offset = docHeight / 4;
 }

//문서의 높이가 정의되어 있지 않다면 offset은 문서높이의 4/1;

//스크롤 이벤트추가 ---> window에 스크롤이 생기면 할일
window.addEventListener('scroll',function(){
scrollPos = docElem.scrollTop;
console.log(scrollPos); 

//btt.className = 'box'; 
//className 클래스명 추가하는게 아니라 클래스명이 없으면 넣고, 있으면 box로 바꾸라는 뜻

//스크롤 양이 offset보다 많으면
btt.className = (scrollPos > offset) ? 'visible' : '';
//==>1. 만약 조건이 참이면 visible클래스명을 추가하고 아니면 빈공란 2. 조건을 나중에쓰자.
// if(scrollPos > offset){
//  btt.className = 'visible';
// } else {
//   btt.className = '';
//  }

});

//클릭하면 html에서 <a id="back-to-top" href="#">Top</a>의 a링크 때문에 위로 확 올라간다.
btt.addEventListener('click',function(ev){
ev.preventDefault(); //링크의 본연의 기능을 막는다.'top'을클릭해도 위로 올라가지않는다. a링크의 기능을 막았기 때문에
//docElem.scrollTop = 0; a링크없애고 0으로 바뀌었더니 위로 올라가긴했는데..그래서 일정시간마다 스크롤양을 줄여서(-55) 0되면 멈추게...
scrollToTop();
});
function scrollToTop(){
//일정시간 마다 할일
//var scrollInterval = setInterval(할일, 시간);
//0.0015s =15
//할일 =function(){실제로 할일}
//실제로 할일 윈도우 스크롤이 0이 아닐때 window.scrollBy(0,-55);
//스크롤이 0이면 setInterval멈춰라, clearInterval(이름);

//var scrollInterval = setInterval(할일, 시간); 대입시키자.
var scrollInterval = setInterval(function(){
if(scrollPos !=0){
 window.scrollBy(0,-55);
}else{
 clearInterval(scrollInterval);
}
}, 15);
}
//위에것 해석 ; 스크롤양이 0이아닐때 window.scrollBy(x,y)에서 y를-55씩 감소시키고
//그렇치않으면(스크롤이 0이면) clearInterval(이름);해라


 </script>
    </body>
</html>