-1
我有一个onkeydown事件,可能会或可能不会滚动页面,并且可能会或可能不会设置变量。我想有一个onscroll事件,将该变量设置为false。我不想让onkeydown事件触发onscroll事件。我怎样才能做到这一点?如何停止发起另一个(不同)事件的JavaScript事件?
编辑:添加了我的代码。它可让您使用左右箭头键上下移动页面上的图像。对不起,它太宽了。
<script>
window.anImageHasBeenCentered = false;
window.onkeydown = function (key)
{
var element = document.elementFromPoint (window.innerWidth/2, window.innerHeight/2);
if (anImageHasBeenCentered) // move to next image
{
switch (window.event ? event.keyCode : key.keyCode)
{
case 37: element = element.parentNode.previousSibling.previousSibling.firstChild; break; // Left Arrow
case 39: element = element.parentNode.nextSibling.nextSibling.firstChild; break; // Right Arrow
default: anImageHasBeenCentered = false; element = null;
}
}
else // center current image
{
switch (window.event ? event.keyCode : key.keyCode)
{
case 37: break; // Left Arrow
case 39: break; // Right Arrow
default: element = null;
}
}
if (element)
{
element.scrollIntoView ();
if ((window.innerHeight + window.scrollY) < document.body.offsetHeight) // if we are not at the bottom of the page
{
if (element.offsetHeight < window.innerHeight) // if the element is shorter than the screen
{ window.scrollBy (0, -((window.innerHeight - element.offsetHeight)/2)) } // position it in the middle of the screen
}
anImageHasBeenCentered = true;
}
};
// The function I would like to add, that is unfortunately triggered by the onkeydown function.
// window.onscroll = function () { anImageHasBeenCentered = false; }
</script>
如果你可以显示一些代码,可以肯定地帮助你 – baao 2014-11-22 03:01:47
你给了event.stopPropagation()方法一下吗? https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation – 2014-11-22 03:04:02
是的。据我了解,stopPropagation只能防止同类型的事件触发。不是另一种类型的事件。 – Yay295 2014-11-22 03:09:01