-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