Heim  >  Artikel  >  Web-Frontend  >  js监听滚动条滚动事件使得某个标签内容始终位于同一位置_javascript技巧

js监听滚动条滚动事件使得某个标签内容始终位于同一位置_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:02:381157Durchsuche

小知识点,废话不多说,直接上代码

css:

复制代码 代码如下:

<style> <BR>#anchor:{ <BR>position:absulate; <BR>top:40%; <BR>left:40%; <BR>width:100px; <BR>height:100px; <BR>background-color:red; <BR>} <BR></style>



js:
复制代码 代码如下:

var auchorTop = $("#anchor").css("top"); <br>auchorTop = Number(auchorTop.substring(0, anchorTop.indexOf("p"))); //首先在监听器外部记录某id=anchor的标签的初始位置 <br>window.onscroll = function () { <br>var top = document.documentElement.scrollTop || document.body.scrollTop; <br>$("#anchor").css("top", anchorTop + top + "px"); <br>};


html:
复制代码 代码如下:



在window.onscroll上即可添加滚动条滚动事件,在监听函数中的top=document.documentElement.scrollTop||document.body.scrollTop;之所以这么写,就是避免不同浏览器的兼容性,这里我测试了chrom和ff浏览器,前者支持document.body.scrollTop这个属性,后者支持另一个属性,因此可以用‘||'符号糅合这两个属性,兼容不同浏览器。anchorTop就是目标的开始与浏览器顶部的距离,这里还需要注意的是'#anchor‘这个标签的position:absulate,否则top属性值总是是0px。

当滚动条滚动时,top值变化,随后将'#anchor'的初始top值加上滚动条的top值,即可保持内容始终处于同一位置。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn