| Grails Version: 3.1.4
| Groovy Version: 2.4.6
| JVM Version: 1.7.0_80
------------------------------------------------------------------------------
------------------------------------------------
最近使用grails时,碰到了一个很神奇的事情,我在gsp页面中使用如下代码,竟然死活
触发不了滚动事件:
<g:javascript>
window.onscroll = function(){
console.log("onscroll...");
}
$(document).ready(function(){
console.log("ready...");
});
// 页面滚动事件
$(window).scroll(function () {
console.log("kkk...");
});
</g:javascript>
------------------------------------------------------------------
xxx.gsp页面代码如下(注意使用了layout,我注释掉layout后是可以正常触发滚动事件的):
<!doctype html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Welcome to Grails</title>
</head>
<body>
<div style="height: 800px; border: 1px solid red;" id="test">div...</div>
<g:javascript>
window.onscroll = function(){
console.log("onscroll...");
}
$(document).ready(function(){
console.log("ready...");
});
//页面滚动事件
$(window).scroll(function () {
console.log("kkk...");
});
</g:javascript>
</body>
</html>
-----------------------------------------------------------------------------------------------
排查了很久,最后发现原因如下:
<meta name="layout" content="main"/> // 这里使用了main.gsp
main.gsp代码片段如下:
<!DOCTYPE html>
<html lang="zh_CN">
<head>
...
<asset:stylesheet src="application.css"/>
...
</head>
....
-----------------------------------
application.css内容如下:
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS file within this directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the top of the
* compiled file, but it's generally better to create a new file per style scope.
*
*= require bootstrap
*= require grails
*= require main
*= require mobile
*= require common
* require_self
*/
可见使用到了grails.css,该文件有如下代码片段:
html, body {
height: 100%;
-webkit-overflow-scrolling: touch;
}
我把 height: 100%; 注释掉后可以正常触发滚动事件了,真是坑呀。
html, body {
/*height: 100%;*/ /* 这行代码会导致window.onscroll无效 */
-webkit-overflow-scrolling: touch;
}
--------------------------------------------------------------------------
后来我单独建了一个html文件来设置以下样式:
html, body {
height: 100%;
-webkit-overflow-scrolling: touch;
}
发现还是可以正常触发滚动事件的,这下就神奇了,至于为什么在grials的gsp页面中为什么会滚动不了,
我现在也不是很清楚了。。。
------------------------------------------------------------------------------------------------------------------------------------------------
经验教训:
1、CSS样式会影响javascript某些事件的发生。