我遇到过类似的问题,我想在 iFrame 上拖动 div。问题是,如果鼠标指针移到 div 之外,移到 iFrame 上,mousemove 事件就会丢失并且 div 停止拖动。如果这是您想要做的事情(而不是仅仅检测用户在 iFrame 上挥动鼠标),我在another question thread 中找到了一个建议,当我尝试它时似乎效果很好。
在包含 和要拖动的东西的页面中,还包括这样的:
<div class="dragSurface" id="dragSurface">
<!-- to capture mouse-moves over the iframe-->
</div>
将其初始样式设置为:
.dragSurface
{
background-image: url('../Images/AlmostTransparent.png');
position: absolute;
z-index: 98;
width: 100%;
visibility: hidden;
}
'98' 的 z-index 是因为我将要拖动的 div 设置为 z-index:99,并将 iFrame 设置为 z-index:0。
当您检测到待拖动对象(而不是 dragSurface div)中的 mousedown 时,调用以下函数作为事件处理程序的一部分:
function activateDragSurface ( surfaceId )
{
var surface = document.getElementById( surfaceId );
if ( surface == null ) return;
if ( typeof window.innerWidth != 'undefined' )
{ viewportheight = window.innerHeight; }
else
{ viewportheight = document.documentElement.clientHeight; }
if ( ( viewportheight > document.body.parentNode.scrollHeight ) && ( viewportheight > document.body.parentNode.clientHeight ) )
{ surface_height = viewportheight; }
else
{
if ( document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight )
{ surface_height = document.body.parentNode.clientHeight; }
else
{ surface_height = document.body.parentNode.scrollHeight; }
}
var surface = document.getElementById( surfaceId );
surface.style.height = surface_height + 'px';
surface.style.visibility = "visible";
}
注意:我从网上找到的其他人的代码中抄袭了大部分代码! 大部分逻辑只是为了设置 dragSurface 的大小以填充框架。
例如,我的 onmousedown 处理程序如下所示:
function dragBegin(elt)
{
if ( document.body.onmousemove == null )
{
dragOffX = ( event.pageX - elt.offsetLeft );
dragOffY = ( event.pageY - elt.offsetTop );
document.body.onmousemove = function () { dragTrack( elt ) };
activateDragSurface( "dragSurface" ); // capture mousemoves over the iframe.
}
}
当拖动停止时,您的 onmouseup 处理程序应包含对此代码的调用:
function deactivateDragSurface( surfaceId )
{
var surface = document.getElementById( surfaceId );
if ( surface != null ) surface.style.visibility = "hidden";
}
最后,您创建背景图像(在我上面的示例中为AlmostTransparent.png),并使其除完全 透明之外的任何内容。我制作了一张 alpha=2 的 8x8 图像。
目前我只在 Chrome 中测试过这个。我也需要让它在 IE 中工作,并将尝试用我在那里发现的内容更新这个答案!