javascript - How in decrease and increase the margin on scroll -



javascript - How in decrease and increase the margin on scroll -

i want write javascript code move text upward decrease margin-top (default 0) when window scrolled up. when scroll down, margin-top of text doesn't equal 0. please help

fiddle example

html:

<div id="h"> <div id="t">hello</div> <div id="content"></div>

css:

#h { background:green; width:550px; height:200px; position:fixed; top:0; padding:50px 0 0 100px; } #t { font-size:40px; color:white; } #content { background:blue; width:550px; height:700px; margin:200px 0; position:relative; }

js:

var pos = 0; var el = document.getelementbyid("t"); var m = 0; window.addeventlistener("scroll", function () { if (window.pageyoffset > pos) { m -= 1; el.style.margintop = m + "px"; } else { m += 1; el.style.margintop = m + "px"; } pos = window.pageyoffset; }, false);

you dont need add together pixel pixel. can set text margin straight scrolltop:

var pos = 0; var el = document.getelementbyid("t"); var m = 0; window.addeventlistener("scroll", function () { el.style.margintop = -window.pageyoffset/2 + "px"; pos = window.pageyoffset; }, false);

fixed example

javascript negative-margin

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -