javascript event.returnValue = false 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17767092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
event.returnValue = false not working
提问by Marius Popescu
I am working on a scrollbar in Javascript. All works fine except for one problem. I notice that while dragging the scrollbar, if I move the mouse over the context that is being scrolled, the content gets selected. I don't want that to happen, so I used the preventDefault
method from the event object, which worked perfectly for IE9 and the other modern browsers. But on IE7 and IE8, the problem persists. I did some searches and found that I should set the returnValue
parameter of the event object to false. But the problem still persists. Also, if I write alert(window.event.returnValue)
it pops up undefined
.
我正在使用 Javascript 处理滚动条。除了一个问题外,一切正常。我注意到在拖动滚动条时,如果我将鼠标移动到正在滚动的上下文上,内容将被选中。我不希望这种情况发生,所以我使用了preventDefault
事件对象中的方法,该方法非常适用于 IE9 和其他现代浏览器。但是在 IE7 和 IE8 上,问题仍然存在。搜索了一下,发现应该returnValue
把事件对象的参数设置为false。但问题仍然存在。另外,如果我写alert(window.event.returnValue)
它会弹出undefined
。
scrollbar.onmousedown = function (event) {
if (typeof event == 'undefined') event = window.event;
if (typeof event.preventDefault != 'undefined') event.preventDefault();
event.returnValue = false;
// do some stuff
}
What am I doing wrong?
我究竟做错了什么?
回答by Lemonade
In IE7&8 there is no event Object as a parameter to the function, instead there exists window.event. Try
在 IE7&8 中没有事件对象作为函数的参数,而是存在 window.event。尝试
window.event.cancelBubble = true
to stop the propagation. To avoid problems with FireFox etc. do something like this:
以停止传播。为避免 FireFox 等出现问题,请执行以下操作:
if (!event)
event = window.event;
//IE9 & Other Browsers
if (event.stopPropagation) {
event.stopPropagation();
}
//IE8 and Lower
else {
event.cancelBubble = true;
}
回答by Marius Popescu
I fixed my problem in the end by adding event.returnValue = false in the 'onmousemove' event, instead on 'onmousedown' event and it worked. It doesn't answer the question about why the orginal code is wrong, but I wanted to post this for people that see my question, to not waste their time in trying to help me with a problem that I have already fixed. Thank you for your quick answers, I appreciate.
我最终通过在 'onmousemove' 事件中添加 event.returnValue = false 来解决我的问题,而不是在 'onmousedown' 事件中,并且它起作用了。它没有回答关于为什么原始代码错误的问题,但我想为看到我问题的人发布这个问题,以免浪费时间来帮助我解决我已经解决的问题。感谢您的快速答复,我很感激。
回答by Sandeep Kamath
I too had the same problem. preventDefault was not working in IE. so I added the below code to stop propagation
我也有同样的问题。preventDefault 在 IE 中不起作用。所以我添加了下面的代码来停止传播
if (a_event.preventDefault) {
a_event.preventDefault();
} else if (typeof a_event.returnValue !== "undefined") {
a_event.returnValue = false;
}