欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > HTML >内容正文

HTML

jQuery兼容IE和Chrom浏览器-得到页面滚动条的坐标值

发布时间:2025/3/21 HTML 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 jQuery兼容IE和Chrom浏览器-得到页面滚动条的坐标值 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我们先来看一下代码:

<html><head><base href="<%=basePath%>"><title>My JSP 'practice_02.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">.all {width:100%;height:120%;}.scroll {width:200px;height:100px;overflow: scroll;}</style></head><body><div class="all"><div class="scroll">this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/></div><button id="btn1">得到scrollTop的坐标</button><button id="btn2">设置scrollTop的坐标</button></div><script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><script type="text/javascript">$('#btn1').click(function() {console.log('以下是滚动条的位置');console.log($('html').scrollTop());});</script></body> </html>

当我们使用Chrome浏览器滚动浏览器的滚动条时发现是每次取的值都是0,如下:

没有滚动的时候

滚动之后

但是在IE浏览器就可以取到值

所以我们将代码做一下修改,修改部分如下:

<script type="text/javascript">$('#btn1').click(function() {console.log('以下是滚动条的位置');console.log($('body').scrollTop());}); </script>

我们发现Chrome浏览器可以取到值了

经过小编测试部分版本的IE浏览器的值为0

所以我们看最终的代码:

<html><head><base href="<%=basePath%>"><title>My JSP 'practice_02.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">.all {width:100%;height:120%;}.scroll {width:200px;height:100px;overflow: scroll;}</style></head><body><div class="all"><div class="scroll">this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/>this is niuniu love<br/></div><button id="btn1">得到scrollTop的坐标</button><button id="btn2">设置scrollTop的坐标</button></div><script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><script type="text/javascript">$('#btn1').click(function() {console.log('以下是滚动条的位置');console.log($('body').scrollTop()+$('html').scrollTop());});</script></body> </html>

总结

以上是生活随笔为你收集整理的jQuery兼容IE和Chrom浏览器-得到页面滚动条的坐标值的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。