出现了这个问题我们总是把时间花在分析为什么iframe这个element不能滑动?该怎么设置?
其实iframe监听滑动如果出了问题,首先该分析的是里面的document到底能不能滑动.
--------------------------------------------------------------------------------------------------------------------------
iframe监听滑动本身其实很简单,只需要iframe的contentWindow增加一个scroll事件的监听即可.
window.addEventListener('scroll', function(e) {
console.log('scrollllllllll')
});
<body>
<p>两个iframe互相触发scroll,形成循环(可以打开控制台,看当前触发scroll的iframe),</p>
<p>(注:safaric上效果不兼容)</p>
<div class='iframe_container' id='iframe1_c'>
<iframe id='iframe1' src='a.html'></iframe>
</div>
<div class='iframe_container' id='iframe2_c'>
<iframe id='iframe2' src='a.html'></iframe>
</div>
<script src='/js/jquery-1.9.0.min.js'></script>
<script>
$(function() {
var iframe1Window,iframe2Window;
$('iframe').on('load', function() {
var contentWindow = $(this)[0].contentWindow,
_id = $(this).attr('id');
if(_id == 'iframe1' && !iframe1Window) {
iframe1Window = contentWindow;
}
if(_id == 'iframe2' && !iframe2Window) {
iframe2Window = contentWindow;
}
contentWindow.onscroll = function(e) {
var scrollTop = $(contentWindow).scrollTop();
console.log(_id);
if(_id == 'iframe1') {
if(iframe2Window) {
$(iframe2Window).scrollTop(scrollTop);
}
} else if(_id == 'iframe2') {
if(iframe1Window) {
$(iframe1Window).scrollTop(scrollTop);
}
}
};
})
})
</script>
</body>
或者iframe.contentDocument增加一个监听事件
可是为什么我的同源协议没为题,可还是监听无法奏效呢?
原因很可能就在于你的那个网页不经过iframe,直接给window或document增加scroll监听都不能用.
不信你测试一下
document.addEventListener('scroll', function(e) {
console.log('scrollllllllll_doc')
});
完后滑动,果然没有输出.
为啥有的document不能监听滑动?
答案,有的document.scrollingElement本身就不可滑动(你滑动的是里面的孩子,而不document.scrollingElement本身,document.scrollingElement本身没有溢出问题,他的孩子有溢出问题,他的孩子产生的scrollbar)
document.scrollingElement的解释
The
scrollingElement
read-only property of the Document interface returns a reference to the Element that scrolls the document. In standards mode, this is the root element of the document, document.documentElement.
用js代码测试元素是否可滑动:
const isScrollable = function (ele) {
// Compare the height to see if the element has scrollable content
const hasScrollableContent = ele.scrollHeight > ele.clientHeight;
// It's not enough because the element's `overflow-y` style can be set as
// * `hidden`
// * `hidden !important`
// In those cases, the scrollbar isn't shown
const overflowYStyle = window.getComputedStyle(ele).overflowY;
const isOverflowHidden = overflowYStyle.indexOf('hidden') !== -1;
return hasScrollableContent && !isOverflowHidden;
};
其中scrollHeight
其中clientHeight
它是元素的内部高度(以像素为单位)。它包括填充但不包括边框、边距和水平滚动条(如果存在)。
在控制台测试一下,就知道你的文档可不可以滑动了.
可以
不可以,但他的孩子page-container可以